user1816467
user1816467

Reputation:

How can I generate all possible strings in a defined character set?

Im trying to use python to define a character set then generate all the possible strings that are the in character set.

I was thinking of first setting the character set as a variable then using for loops to generate the possible strings like this:

charSet = [a-zA-Z0-9]
for a in charSet:
      print (a)
for b in charSet:
      print (b)

But i keep getting this error message UnboundLocalError: local variable 'a' referenced before assignment

Any ideas anyone?

Upvotes: 2

Views: 1790

Answers (2)

PaulMcG
PaulMcG

Reputation: 63709

Once you get your charSet definition problem resolved, look at itertools.product:

from itertools import product
import string

charSet = string.ascii_letters + string.digits
for wordchars in product(charSet, repeat=4):
    print ''.join(wordchars)

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838146

There is no builtin syntax similar to what you are looking for, however there are some predefined strings that contain the letters you need:

import string
charSet = string.ascii_letters + string.digits

For a more general solution you could try this function:

def getCharactersFromCharSet(charSet):
    import re
    chars = []
    for c in re.findall('.-.|.', charSet):
        if len(c) == 1:
            chars.append(c)
        else:
            for i in range(ord(c[0]), ord(c[2]) + 1):
                chars.append(chr(i))
    return ''.join(chars)

print getCharactersFromCharSet('a-zA-Z0-9')

Upvotes: 2

Related Questions