Home > Software design >  How to turn strings into operations?
How to turn strings into operations?

Time:07-21

I recently tried to find polynomials with given points and stumbled upon the problem that I can’t use strings like normal mathematical operations: "3 1" "2 1" because it will return "3 12 1". I than tried to just iterate over the string but had the next difficulty that I cant just unstringify operations like " " or "-".

Does anyone know how to do solve the problem?

CodePudding user response:

eval() is very dangerous

It can execute any commands, including unsafe or malicious strings.

Use Pyparsing (more info here and another question and example here).

Another option is the ast module (good example here). If you want more functionality, ast can open up more commands, but pyparsing should work well.

A third, more lightweight option is this single file parser

CodePudding user response:

If this calculation will exist purely within the code, with the user having no direct access, then you can use eval().

Example:

print(eval("3   4"))

Output:

7

The point of eval() is to execute Python code that is stored as a string. If the user is inputting values to be used within an eval() statement, you should absolutely do some error-checking to make sure the user is inputting numbers. If your program was intended to be released for commercial use, say, you run the risk of a user inputting Python code that can be executed using eval().

  • Related