Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我们能从字符串中提取数字并将它们相乘吗_Python_Numbers - Fatal编程技术网

Python 我们能从字符串中提取数字并将它们相乘吗

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

我正在尝试制作一个程序,可以从字符串中提取所有的数字,并将它们相乘,就像字符串是“相乘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

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)}')

如果命令不受数学的限制,那么您基本上是在询问编译器/解释器理论。如果需要,请尝试按空格拆分单词,使用字符串方法检查它是数字还是文本。