Incrementing a string

Phil Frost indigo at bitglue.com
Wed Sep 15 22:55:16 EDT 2004


#### begin sample program ####

import string

class LabelCounter(object):
    digits = string.lowercase

    def __init__(self, value=0):
        self.value = value

    def __str__(self):
        letters = []
        i = self.value
        while i:
            d, m = divmod(i, len(self.digits))
            letters.append(self.digits[m])
            i = d
        return ''.join(letters[::-1]) or self.digits[0]

    def __add__(self, other):
        return LabelCounter(self.value + other)

    def __lt__(self, other):
        return self.value < other

    # define other operators as needed; it's a shame this can't inherit from
    # int and get these for free. It can't do this because all of int's
    # operators return ints, not LabelCounters.


i = LabelCounter(0)
while i < 50:
    print i
    i += 1

#### end sample program ####

You can set 'digits' to any sequence at all. Set it to '01' to get
output in binary, or to ['01','23','45','67','89'] to get base 5 in a
very confusing notation *g*

On Wed, Sep 15, 2004 at 03:08:20PM -0700, John Velman wrote:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list