Reputation: 5972
I have script like:
from string import digits, uppercase, lowercase, punctuation
from itertools import product
chars = lowercase + uppercase + digits + punctuation
for n in range(1, 2+1):
for comb in product(chars, repeat=n):
print ''.join(comb)
it works fine. Imagine chars
is giving by an external user so:
import sys
from string import digits, uppercase, lowercase, punctuation
from itertools import product
chars = sys.argv[1] # sys.argv[1] is 'lowercase+uppercase+digits+punctuation'
for n in range(1, 2+1):
for comb in product(chars, repeat=n):
print ''.join(comb)
when run script.py: It has not the result when you say:
chars = lowercase + uppercase + digits + punctuation
Now how can I get the previous result?
Upvotes: 2
Views: 48
Reputation: 78690
You can use a dictionary mapping the user input to the corresponding strings.
>>> input_to_chars = {
... 'lowercase': lowercase,
... 'uppercase': uppercase,
... 'digits': digits,
... 'punctuation': punctuation
... }
Construct chars
from the user input like this:
>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(input_to_chars[i] for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Or with the hint from @schwobaseggl in the comments:
>>> import string
>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(getattr(string, i) for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
The dictionary solution is easy to extend, the getattr
solution is good if you don't want to extend your program to accept user inputs which are not attributes of string
.
Upvotes: 3