python - 将函数作为字符串获取然后运行它

标签 python string

我有这样的脚本:

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

现在我怎样才能得到之前的结果?

最佳答案

您可以使用字典将用户输入映射到相应的字符串。

>>> 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!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

字典解决方案很容易扩展,如果您不想扩展程序以接受不是 string 属性的用户输入,则 getattr 解决方案是很好的选择.

关于python - 将函数作为字符串获取然后运行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35391900/

相关文章:

Python numpy : Updating multiple columns using lists failed in V1. 10.1

python - Django REST Framework 嵌套序列化器 FK 创建

python - django 单击按钮返回同一页面

jQuery 删除一个单词到字符串中

python - 如何将 block 转换为 block 对角矩阵 (NumPy)

python - 在 Python 中加入整数列表的最简单方法?

C++ 误用模板或编译器字符串文字与模板比较的问题

欧洲日期的正则表达式/正则表达式 ("j. F Y")

php - 将 MD5 哈希表示为整数

string - 具有字符串索引的多级 slice