Transform string "+" or "*" into arithmetic operators | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Transform string "+" or "*" into arithmetic operators

We can convert a string to a number: int("5") => 5 Can we transform string "+" or "*" into arithmetic operators?(without eval())

8th Apr 2020, 5:32 PM
Александр Васильев
Александр Васильев - avatar
6 Answers
+ 2
You can do something like this: from operator import add, mul op = {'+': add, '*': mul} print(op['+'](2, 3)) # 2+3=5 print(op['*'](2, 3)) # 2*3=6 https://code.sololearn.com/cBp52U0M2ysS/?ref=app
8th Apr 2020, 6:00 PM
Tibor Santa
Tibor Santa - avatar
+ 3
Yes we can try this: x=chr(ord("+")) print(x) >>> + And, x=chr(ord("*")) print(x) >>> *
8th Apr 2020, 5:44 PM
Valmob101
Valmob101 - avatar
+ 1
Tibor Santa, closest
10th Apr 2020, 11:56 AM
Александр Васильев
Александр Васильев - avatar
+ 1
You may find answer in https://javascript.info/operators
10th Apr 2020, 1:43 PM
narayanaprasad
narayanaprasad - avatar
0
Not directly I don't think. You can use if if symbol == "+": print(a+b) Or exec exec("print(a" + symbol + "b)")
8th Apr 2020, 5:35 PM
Russ
Russ - avatar
0
L3ARN3R, this is the same
10th Apr 2020, 11:54 AM
Александр Васильев
Александр Васильев - avatar