Search code examples
pythonstringpython-3.xoperation

How to perform math operation on numbers in string of python


How we can perform mathematical operation on string in 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.

eval('10+5*10') which gives 60 but it will not handle characters.


Solution

  • This might help. Use the isalpha method to remove all alpha chars and the use eval

    Ex:

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

    Output:

    60