有一种方法,eval
函数..
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> eval(x)
8
但一定要验证输入只有数字和符号。
>>> def verify(x):
for i in x:
if i not in '1234567890.+-/*%( )':
return False
return True
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> if verify(x):
print eval(x)
8
ast.literal_eval
不起作用:
>>> ast.literal_eval('2+3')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
ast.literal_eval('2+3')
File "C:\Python2.7 For Chintoo\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "C:\Python2.7 For Chintoo\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string