March 09, 2005
Incrementing strings

While I'm posting silly little Python scripts, here's one I prepared earlier.

def inc_string(string, allowGrowth=True):
    '''Increment a string.'''
    CHAR_RANGES = [
                   Bunch(from_char=48, to_char=57),  # digits
                   Bunch(from_char=65, to_char=90),  # upper case
                   Bunch(from_char=97, to_char=122), # 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.

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. (OK, actually, it doesn't - but it's a whole lot easier to access if you stick to 10 characters.) 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, and the column and table names were not a great deal less readable than an RPG programmer is used to anyway. ;-) But I was getting the occasional duplicate, so I came up with this.

(inc_string.py formatted, with unit tests)

Posted to Python by Simon Brunning at March 09, 2005 02:59 PM
Comments
Post a comment
Name:


Email Address:


URL:



Comments:


Remember info?