我的脚本如下:
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)
它工作正常。想象一下chars
由外部用户提供:
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)
运行script.py时: 当你说:
时,它没有结果chars = lowercase + uppercase + digits + punctuation
现在我怎样才能得到以前的结果?
答案 0 :(得分:3)
您可以使用将用户输入映射到相应字符串的字典。
>>> input_to_chars = {
... 'lowercase': lowercase,
... 'uppercase': uppercase,
... 'digits': digits,
... 'punctuation': punctuation
... }
从用户输入中构造chars
,如下所示:
>>> 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!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
或者在评论中提及@schwobaseggl的提示:
>>> 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!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
字典解决方案很容易扩展,如果您不希望扩展程序以接受不属于getattr
属性的用户输入,则string
解决方案很好。