One way to do this is to take the pattern and replace each char with the number that should be there and then eval
the result
(一种方法是采用模式并将每个字符替换为应该存在的数字,然后eval
结果)
string.ascii_letters
is a string of all ascii characters in alphabetical order starting with lowercase.
(string.ascii_letters
是所有ASCII字符的字符串,按字母顺序string.ascii_letters
写开始。)
This can be used to convert the char into the index of the digit that should be extracted from n
(这可用于将char转换为应从n
提取的数字的索引)
>>> [n[string.ascii_letters.index(x)] if x in string.ascii_letters else x for x in pattern]
['3', '-', '4', '1', '3', '2', '8', '9', '8', '3', '0']
We add if x in string.ascii_letters else x
so that the operators are not converted.
(我们if x in string.ascii_letters else x
添加if x in string.ascii_letters else x
以便不转换运算符。)
Then you join the resulting list to get the string (然后,您加入结果列表以获取字符串)
>>> ''.join(n[string.ascii_letters.index(x)] if x in string.ascii_letters else x for x in pattern)
'3-413289830'
Removing the brackets turns the list comprehension into a generator which should be slightly more performant.
(删除括号将列表理解变成一个生成器,它应该会稍微好一些。)
You can then use eval
to run this string as if it was python code (然后,您可以使用eval
来运行此字符串,就好像它是python代码一样)
>>> eval(''.join(n[string.ascii_letters.index(x)] if x in string.ascii_letters else x for x in pattern))
-413289827
You should only use eval if you trust the input that you are being given as it can execute arbitrary code
(仅当您信任输入信息时,才应使用eval,因为它可以执行任意代码)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…