R
R
Rip_Hunter2020-07-28 23:14:40
Python
Rip_Hunter, 2020-07-28 23:14:40

Converting characters in Python to int?

Could you please tell me why Python can't translate math characters (*, +, - ...) from str to int? The essence of the problem is that I have a string "150 x 81" (with spaces) and I need to calculate this example. If you just replace "x" with "*", then after python does not allow you to convert "*" to int type.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim, 2020-07-28
@Rip_Hunter

I don't know why you need this, but it works great:

>>> literal_expr = '150 x 81'
>>> eval(literal_expr.replace('x', '*'))
12150

A
Andrey, 2020-07-28
@anerev

Op:

x = '150 x 81'
x1 = x.split('x')
y = int(x1[0]) * int(x1[1]) #12150

A
Andrey Ivanov, 2020-07-29
@TomRiddle

The operators +, *, -, / have no type - they do not refer to int, float, or bool, so they cannot be converted to any type.
But you can count them and set the operation algorithm. Here is one option for multiplication. By analogy, it can be used with other operations (/, +, -, **, //, etc.)

string = "150 x 5"
for index in range(len(string.split())):
    if string.split()[index] == "x":
        answer = int(string.split()[index-1]) * int(string.split()[index+1])
print (answer)

But it is suitable for a simple equation with two numbers. If the equations are more complex, then it is better to use the eval(string) function. This function will also save the algebraic rules (first do multiplication and division, operations in brackets, and then addition and subtraction, etc.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question