Incrementing a string

Paul Rubin http
Thu Sep 16 07:15:13 CEST 2004


Here's my generator version:

    def gen_alph():
        def convert(k,n):
            # convert integer k to n-letter string
            out = []
            for i in xrange(n):
                k,r = divmod(k,26)
                out.append(chr(97+r))
            out.reverse()
            return ''.join(out)

        nletters = 1
        while True:
            for k in xrange(26**nletters):
                yield convert(k, nletters)
            nletters += 1

To test it:

    g = gen_alph()
    for i in range(40):
        print i, g.next()



More information about the Python-list mailing list