Incrementing a string

John Velman velman at cox.net
Thu Sep 16 00:08:20 CEST 2004


I've used perl for a lot of 'throw away' scripts;  I like Python better in
principle, from reading about it, but it was always easier to just use
perl rather than learn python.

Now I'm writing a smallish program that I expect to keep around, so am
taking this opportunity to try to learn some Python.  I have a need for
computer generated set of simple string lables.  I don't know how many in
advance---each is produced as a result of a user action.

In perl I simply initiated
 
   $label= "a";

Then, after using it doing

    $label++;

This conveniently steps through the alphabet, then goes on to aa, ab,ac,
...

In Python I can get from a to z with a generator as so:

>>> def gen_alph():
...     for i in range(97,123):
...         yield chr(i)
...
>>> g = gen_alph()
>>> g.next()
'a'
>>> g.next()
'b'
>>> g.next()
'c'

But it looks like going beyond z to aa and so on is (relatively) complicated.

In truth, it seems unlikely that I would ever go beyond z in using my
application, and certainly not beyond zz which wouldn't be too hard to
program.  But I hate to build in limitations no matter how reasonable.

It seems like there should be a better way that I'm missing because I'm
thinking in perl, not thinking in Python.  :-)

Best,

John Velman



More information about the Python-list mailing list