Python: determine if a string contains math?

前端 未结 3 1217
清酒与你
清酒与你 2021-01-23 11:46

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

3条回答
  •  梦毁少年i
    2021-01-23 12:02

    Simply use split(), then iterate through the list to check if all instance are either numerical values or operational values. Then use eval.

    input = "1 + 2"
    for i in input.split():
        if i in ['+','-','*','%','.'] or i.isdigit():
            pass
            # do something
        else:
            pass
            # one element is neither a numerical value or operational value
    

提交回复
热议问题