Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn string into operator

How can I turn a string such as "+" into the operator plus?

like image 420
hwong557 Avatar asked Nov 16 '09 08:11

hwong557


People also ask

How do you turn a string into an operator?

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.

How can I convert a string into a math operator in JavaScript?

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.

How do you make a string operator in Python?

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.

Is an operator a string?

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 (' .


1 Answers

Use a lookup table:

import operator ops = { "+": operator.add, "-": operator.sub } # etc.  print(ops["+"](1,1)) # prints 2  
like image 155
Amnon Avatar answered Oct 07 '22 17:10

Amnon