Search code examples
pythonstringloopsscriptingalphabet

Python: Cycle Through the Alphabet


I'm creating a script that cycles through the alphabet, after that a new letter is added that cycles through again. Here's my code so far:

import string
for a in (string.ascii_letters + string.digits):
    print (a)
for a in (string.ascii_letters + string.digits):
    for b in (string.ascii_letters + string.digits):
        print(a + b)
for a in (string.ascii_letters + string.digits):
    for b in (string.ascii_letters + string.digits):
        print(a + b)
        for c in (string.ascii_letters + string.digits):
            print(a + b + c)

What is a more efficient way of doing this?


Solution

  • The itertools module will let you define an infinite stream of such strings.

    import string
    import itertools
    
    def alphanumeric_strings():
        for n in itertools.count():
            for t in itertools.product(string.ascii_letters + string.digits, repeat=n):
                yield ''.join(t)
    
    for x in alphanumeric_strings():
        print x
    

    count simply produces an infinite stream of integers counting up from 1, so that each time you call product, you get a stream of tuples with one more digit than the last. The call to join converts a tuple like ('a', 'B', '1') to the string aB1.