Python 我们能从字符串中提取数字并将它们相乘吗
我正在尝试制作一个程序,可以从字符串中提取所有的数字,并将它们相乘,就像字符串是“相乘30和50”,然后程序应该能够删除空格和字母,并将剩余的数字相乘,数字可以超过2,你能告诉我怎么做吗Python 我们能从字符串中提取数字并将它们相乘吗,python,numbers,Python,Numbers,我正在尝试制作一个程序,可以从字符串中提取所有的数字,并将它们相乘,就像字符串是“相乘30和50”,然后程序应该能够删除空格和字母,并将剩余的数字相乘,数字可以超过2,你能告诉我怎么做吗 test = '*'.join(c for c in "multiply 30 and 50" if c.isdigit()) print(f'answer is {test}') 结果应该是1500您可以使用正则表达式: from re import compile as recompile numbe
test = '*'.join(c for c in "multiply 30 and 50" if c.isdigit())
print(f'answer is {test}')
结果应该是1500您可以使用正则表达式:
from re import compile as recompile
numbers = recompile(r'\d+')
然后可以使用reduce
和mul
将数字相乘,如:
from functools import reduce
from operator import mul
query = 'multiply 30 and 50'
result = reduce(mul, map(int, numbers.findall(query)))
这就给了我们:
>>> result
1500
这当然不考虑“乘法…和…”部分,因此如果它是“从10中减去5”,它仍然会返回50
如果您想制作一个更高级的系统,从而不仅仅查找字符串中的数字,那么您应该实现一个,例如使用一个。类似于您尝试的方法,但可以工作:
s = 'multiply 5 by 10'
import re
s = '*'.join(re.findall('\d+',s))
print(f'{eval(s)}')
如果命令不受数学的限制,那么您基本上是在询问编译器/解释器理论。如果需要,请尝试按空格拆分单词,使用字符串方法检查它是数字还是文本。