1

I have a question about how to convert strings with arithmetic operations like + or * from a string to an integer.

Here is my input and the error output:

    a = int('4*5')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '4*5'

I've expected this operation saves the number 20 as an interger in variable a.

Thanks for helping

lghh
  • 184
  • 1
  • 11

4 Answers4

3

It is evaluating the string as a whole as an integer without applying the mathematical operations present within the string, so obviously this fails, as * is not a valid digit.

There are certain ways to take code like this and evaluate it that can also be dangerous, such as eval. However, there is a library called pandas which has a much safer eval function:

From the pandas documentation:

The following arithmetic operations are supported: +, -, *, /, **, %, // (python engine only) along with the following boolean operations: | (or), & (and), and ~ (not)

>>> import pandas as pd
>>> pd.eval('4*5')
20 

This is a much safer alternative to using plain eval, which can run potentially malicious code on your machine.

user3483203
  • 50,081
  • 9
  • 65
  • 94
1

You're looking for eval:

>>> a = eval('4 * 5')
>>> a
20
>>> type(a)
<type 'int'>

Caveat: BE CAREFUL WITH THIS. eval() will evaluate mathematical expressions like this one, but will also execute any valid python code it's given. For example,

>>> eval( 'type(a)' )
<type 'int'>
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

If you must take the expression as a string, use Python's eval function.

a = eval('4*5')
a
> 20

Otherwise, just remove the quotes to make it an expression instead of a string:

a = 4*5
a
> 20
GetHacked
  • 546
  • 4
  • 21
0

The dangerous way is to use the eval function. eval is quite powerful, and often results in unexpected or unwanted behaviour from small errors in the input.

To do this properly, you need to process the string. Extract each of the numerical strings and the operation. Convert the strings to ints, then test the operation and apply the needed code. For instance:

expr = '4*5'
num1 = int(expr[0])
num2 = int(expr[2])
op = expr[1]

if op == '*':
    result = num1 * num2

In general, Python language syntax (keywords, math symbols, punctuation, etc.) are not easily transferred between the program itself and the data you're using.

Prune
  • 76,765
  • 14
  • 60
  • 81