Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate alphanumeric strings sequentially

I'm trying to create a loop to generate and print strings as follows:

  1. Alphanumeric characters only:
  2. 0-9 are before A-Z, which are before a-z,
  3. Length goes up to 4 characters.

So, it would print:

  1. all strings from 0-z
  2. then from 00-zz
  3. then from 000-zzz
  4. then from 0000-zzzz

then it stops.

like image 395
joseph Avatar asked Aug 20 '11 18:08

joseph


1 Answers

from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product

chars = digits + ascii_uppercase + ascii_lowercase

for n in range(1, 4 + 1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

This first makes a string of all the numbers, uppercase letters, and lowercase letters.

Then, for each length from 1-4, it prints every possible combination of those numbers and letters.

Keep in mind this is A LOT of combinations -- 62^4 + 62^3 + 62^2 + 62.

like image 153
agf Avatar answered Oct 04 '22 14:10

agf