How can I turn a string such as "+"
into the operator plus?
To turn string into operator with Python, we can use the operator module. to create the ops dict that has the operator strings as keys and the operators as the values. Then we can get the operator by the string key and use them with operands.
To convert a string into a math operator in JavaScript, we use the mathjs package. import { evaluate } from "mathjs"; const myArray = ["225", "+", "15", "-", "10"]; const result = evaluate(myArray.
The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times. Writing two string literals together also concatenates them like + operator.
There are two string operators. The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' .
Use a lookup table:
import operator ops = { "+": operator.add, "-": operator.sub } # etc. print(ops["+"](1,1)) # prints 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With