The story behind this one is that I was building a database conversion utility, converting both schema and data from one database engine to another. Thing was, the target database only allows 10 characters in its table and column names. I stripped down the longer entity names by removing whitespace and spacing characters, then non-leading vowels, and at the last resort, I truncated.
This worked on the whole, but I was getting the occasional duplicate, so I came up with this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | def inc_string(string, allowGrowth=True):
'''Increment a string.'''
CHAR_RANGES = [
Bunch(from_char=ord('0'), to_char=ord('9')), # digits
Bunch(from_char=ord('A'), to_char=ord('Z')), # upper case
Bunch(from_char=ord('a'), to_char=ord('z')), # lower case
]
string_chars = list(string)
string_chars[-1] = chr(ord(string_chars[-1]) + 1)
for index in range(-1, -len(string_chars), -1):
for char_range in CHAR_RANGES:
if ord(string_chars[index]) == char_range.to_char + 1:
string_chars[index] = chr(char_range.from_char)
string_chars[index-1] = chr(ord(string_chars[index-1]) + 1)
for char_range in CHAR_RANGES:
if ord(string_chars[0]) == char_range.to_char + 1:
if allowGrowth:
string_chars[0] = chr(char_range.from_char)
string_chars.insert(0, chr(char_range.from_char))
else:
raise ValueError, string + " cannot be incremented."
return ''.join(string_chars)
|
Requires the martellibot's Bunch class - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308.
Thanks to Marius Gedminas for suggesting using ord() rather than hand coding the char values.