+ 1

Help

How can I get convert a user input from a string to a symbol such as / * %+- without specifying every symbol

5th Sep 2018, 5:04 AM
Jonathan Wodzisz
Jonathan Wodzisz - avatar
2 Answers
+ 12
As evil as it is, you have eval() https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/methods/built-in/eval E.g. a = "5" b = "39" c = input() print(eval(a+c+b)) Let's say you input "+", the output would be 44.
5th Sep 2018, 5:11 AM
Hatsy Rei
Hatsy Rei - avatar
+ 11
Based on: https://stackoverflow.com/questions/1740726/turn-string-into-operator a = 5 b = 39 c = input() ops = { "+": (lambda x,y: x+y), "-": (lambda x,y: x-y), "/": (lambda x,y: x/y), "*": (lambda x,y: x*y) } print(ops[c](a,b))
5th Sep 2018, 5:49 AM
Maz
Maz - avatar