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?
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?
Are the answers at http://stackoverflow.com/questions/604721/how-would-you-translate-this-from-perl-to-python/604777 sufficient? Not 100% what you're asking, but close...
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.
A different, longer, but perhaps more readable and flexible solution:
def toval(s):
"""Converts an 'azz' string into a number"""
v = 0
for c in s.lower():
v = v * 26 + ord(c) - ord('a')
return v
def tostr(v, minlen=0):
"""Converts a number into 'azz' string"""
s = ''
while v or len(s) < minlen:
s = chr(ord('a') + v % 26) + s
v /= 26
return s
def next(s, minlen=0):
return tostr(toval(s) + 1, minlen)
s = ""
for i in range(100):
s = next(s, 5)
print s
You convert the string into a number where each letter represents a digit in base 26, increase the number by one and convert the number back into the string. This way you can do arbitrary math on values represented as strings of letters.
The ''minlen'' parameter controls how many digits the result will have (since 0 == a == aaaaa).