Python:确定一个字符串是否包含数学?

1 python math python-3.x python-3.5

鉴于这些字符串:

"1 + 2"
"apple,pear"
Run Code Online (Sandbox Code Playgroud)

我如何使用Python 3(.5)来确定第一个字符串是否包含数学问题而没有其他内容,第二个字符串不包含?

klo*_*ffy 7

这是一种方法:

import ast

UNARY_OPS = (ast.UAdd, ast.USub)
BINARY_OPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)

def is_arithmetic(s):
    def _is_arithmetic(node):
        if isinstance(node, ast.Num):
            return True
        elif isinstance(node, ast.Expression):
            return _is_arithmetic(node.body)
        elif isinstance(node, ast.UnaryOp):
            valid_op = isinstance(node.op, UNARY_OPS)
            return valid_op and _is_arithmetic(node.operand)
        elif isinstance(node, ast.BinOp):
            valid_op = isinstance(node.op, BINARY_OPS)
            return valid_op and _is_arithmetic(node.left) and _is_arithmetic(node.right)
        else:
            raise ValueError('Unsupported type {}'.format(node))

    try:
        return _is_arithmetic(ast.parse(s, mode='eval'))
    except (SyntaxError, ValueError):
        return False
Run Code Online (Sandbox Code Playgroud)