Python generate all possible strings of length n

Here's a piece of code that uses [Python 3.Docs]: itertools.product(*iterables, repeat=1).
Note that the number of generated strings is 62 ** length, so for testing purposes use small values for length:

import string
import itertools


def generate_strings(length=3):
    chars = string.ascii_letters + string.digits  # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for item in itertools.product(chars, repeat=length):
        yield "".join(item)

You could use itertools.product:

print([''.join(x) for x in itertools.product('abcABC123', repeat=3)])
['aaa',
 'aab',
 'aac',
 'aaA',
 'aaB',
 'aaC',
 'aa1',
 'aa2',
 'aa3',
 'aba',
...

Just add the remaining characters you need to the input string. You can use the constants from the strings module for this.

Be aware that this quickly grows. ;)


Use itertools.product

from itertools import product
from string import ascii_letters, digits

for i in product(ascii_letters + digits, repeat=n):
    print(''.join(i))

Tags:

Python