I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).
f("aaa")="aab"
f("aaZ")="aba"
And so on.
Is there a function for this in one of the modules already?
Python next() function is used to fetch next item from the collection. It takes two arguments an iterator and a default value and returns an element. This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.
A simple approach: Store the string to a character array and sort the array. If the characters in the sorted array are in the same order as the string then print 'In alphabetical order '. Print 'Not in alphabetical order' otherwise.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
I don't think there's a built-in function to do this. The following should work:
def next_string(s):
strip_zs = s.rstrip('z')
if strip_zs:
return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs))
else:
return 'a' * (len(s) + 1)
Explanation: you find the last character which is not a z
, increment it, and replace all of the characters after it with a
's. If the entire string is z
's, then return a string of all a
's that is one longer.
Are the answers at How would you translate this from Perl to Python? sufficient? Not 100% what you're asking, but close...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With