Given these strings:
"1 + 2"
"apple,pear"
How can I use Python 3(.5) to determine that the first string contains a math problem and nothing else and that the second string does not?
Given these strings:
"1 + 2"
"apple,pear"
How can I use Python 3(.5) to determine that the first string contains a math problem and nothing else and that the second string does not?
Simply use split(), then iterate through the list to check if all instance are either numerical values or operational values. Then use eval.
You can use a parsing library such as pyPEG, although there is room for improvment do more than this you could define a grammar like this:
You can handle the error when an invalid expression is passed through and use the parse function to validate expressions:
Here is a way to do it: