1

I'm working with python 3, and I would like to convert a string like

'2*2*3*5'

into the integer

2*2*3*5 = 60

I have a dictionary with a lot of strings like that, and I need to use them as integers. Is there a fast way to do this? I have tought of using split but I'm having some trouble doing this.

Thanks for the answers.

  • You should **not** use `eval`. Have a look at this [similar question](http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) instead. – Nicolas Apr 15 '14 at 17:25
  • Also, perhaps you could write a simple parser for your strings. Are your expressions more complex than just x*y*z ? – Nicolas Apr 15 '14 at 17:28
  • 2
    *eval* is not necessarily a bad thing. It depends, of course, on the source of the data. If they are from a static, carefully checked file than no solution can be more efficient. – Roberto Reale Apr 15 '14 at 17:30

2 Answers2

3

If it is acceptable to use eval (i.e., your data must be carefully checked in order to prevent unwanted execution of code), you can try:

str = '2*2*3*5'

print eval(str)
Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
2

If all your expressions are repeated multiplication, you can do it like this (no eval):

>>> from functools import reduce
>>> from operator import mul
>>> reduce(mul, [int(term) for term in '2*2*3*5'.split('*')])
60
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82