-2

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.

Akash Kinwad
  • 704
  • 2
  • 7
  • 22

2 Answers2

2

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

Simple:

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

The result is 0.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    recommending `eval` without the security caveat?? – Chris_Rands Feb 26 '18 at 13:22
  • Thanks for answer but eval works only with integer, I want to perform operation with more complexity – Akash Kinwad Feb 26 '18 at 13:31
  • @MrT I am reading txt file, variables are not pre-defined & don't want to consider while calculations – Akash Kinwad Feb 26 '18 at 13:45
  • @MrT Whats your problem? My question is clear already, you considered a = 2.7 and something which has no any relation to my question. Why you are interested in my question even if you don't understand the question properly and not able to answer my question. – Akash Kinwad Feb 26 '18 at 14:02