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

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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'>

1 Comment

It Works :-) Thanks for helping and your advice
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

10 Comments

Then int is redundant ... Why is this upvoted ?
Question literally says "convert strings with arithmetic operations"
@scharette You're right. I usually like to edit as little as possible from the original question, but in this case it's unhelpful. Thanks!
@user3483203 I know it does, but I could also suggestint(int(4*5)) following this logic...
@scharette, you can just do int(eval('4 * 5')) if you really want to make sure it returns an integer.
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.