0

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.

Rio
  • 1
  • 1

3 Answers3

0

For this case you can use eval. eval("1*2") will return 2 as int

SPARTACUS5329
  • 133
  • 10
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