有一個辦法,eval
功能...
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> eval(x)
8
但是一定要驗證輸入只有h作爲數字和符號。
>>> 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
嗯,轉換與postfix然後評估... – 2013-05-04 18:15:44
'eval'實際上是不正是這樣的功能! – 2013-05-04 18:17:09
哦,我什至不知道存在,謝謝!它現在有效。 – 2013-05-04 18:17:44