Incrementing a string

Kjetil Torgrim Homme kjetilho at yksi.ifi.uio.no
Thu Sep 16 03:15:28 CEST 2004


[John Velman]:
>
>   [how do I implement "$a = 'z'; $a++;" in Python?]

is there any reason you need your labels to be on this format?
usually, I would find a plain "L42" more readable.

def gen_label():
    num = 0
    while True:
        num += 1
        yield "L" + str(num)


Perl's increment operator isn't a generator, it just changes the
current value so you can jump back and forth.  here's one quick go at
it.  I'm sure it can be done more prettily, and probably without
assuming the string is ASCII :-)

def incr(s):
    i = 1
    while i <= len(s):
        if 'a' <= s[-i] < 'z':
            return s[:-i] + chr(88 + int(s[-i], 36)) + s[len(s)+1-i:]
        elif s[-i] == 'z':
            s = s[:-i] + 'a' + s[len(s)+1-i:]
        else:
            raise ValueError
        i += 1
    return 'a' + s

-- 
Kjetil T.



More information about the Python-list mailing list