Is there a way to change "1 * 2" into a line that would be able to output 2. I couldn't just do int("1 * 2") because the * is not an integer; so I want to find out if there is a way to change * from a string back into its normal form.
Asked
Active
Viewed 52 times
3 Answers
0
For this case you can use eval
.
eval("1*2")
will return
2 as int

SPARTACUS5329
- 133
- 10
-
wow thanks it worked :)))) – Rio Nov 03 '21 at 04:48
-
you should upvote and approve answers if they solve your query, specially for future references – SPARTACUS5329 Nov 03 '21 at 12:51
0
str="1*2*3*4"
eval(str) # this will give 24 as result

karel
- 5,489
- 46
- 45
- 50

keshav swami
- 551
- 1
- 6
- 11
0
s = "5 * 2"
chars = s.split(" ")
def result(x):
return {
'*': int(chars[0]) * int(chars[2]),
'/': int(chars[0]) / int(chars[2]),
'+': int(chars[0]) + int(chars[2]),
'-': int(chars[0]) - int(chars[2]),
'%': int(chars[0]) % int(chars[2])
}[x]
print(result(chars[1]))
I love python

Martin Bekkos
- 46
- 3