Answer the question
In order to leave comments, you need to log in
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
I don't know why you need this, but it works great:
>>> literal_expr = '150 x 81'
>>> eval(literal_expr.replace('x', '*'))
12150
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question