简体   繁体   English

如何对python字符串中的数字执行数学运算

[英]How to perform math operation on numbers in string of python

How we can perform mathematical operation on string in python.我们如何在 python 中对字符串执行数学运算。

Consider below example考虑下面的例子

with open('/home/akashk/projects/math.txt') as f:
    content = f.readlines()
content = [x.strip() for x in content] 

for x in content:
    print(x)
    print(type(x))

output is like输出就像

1abc0+5*1hv0

I want to perform operation using operand and operators我想使用操作数和运算符执行操作

above should be considered as 10+5*10 = 60 In short remove characters and perform mathematical operation on operands.以上应视为 10+5*10 = 60 简而言之,删除字符并对操作数进行数学运算。

eval('10+5*10') which gives 60 but it will not handle characters. eval('10+5*10') 给出 60 但它不会处理字符。

This might help.这可能会有所帮助。 Use the isalpha method to remove all alpha chars and the use eval使用isalpha方法删除所有 alpha 字符并使用eval

Ex:前任:

s = "1abc0+5*1hv0"
s = "".join([i for i in s if not i.isalpha()])
print eval(s)

Output :输出

60

Simple:简单的:

eval('10/2%2-1')

The result is 0.结果是0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM