[英]String to Int conversion in python
If I have a string "2+3", is there anyway to convert it to an integer so it comes out as 5? 如果我有一个字符串“ 2 + 3”,是否有将其转换为整数以使其为5的结果?
I tried this: 我尝试了这个:
string = 2+3
answer = int(string)
But I get an error: 但是我得到一个错误:
ValueError: invalid literal for int() with base 10: '2+3'
I'm trying to take a fully parenthesized equation and use stacks to answer it. 我正在尝试采用完全括号括起来的方程式,并使用堆栈来回答它。
ex. 例如 Equation = ((2+3) - (4*1)) 等式=((2 + 3)-(4 * 1))
I tried taking the equation as an input, but python just solves it on its own. 我尝试将方程式作为输入,但是python只能自行解决。 So to avoid that problem, I took the equation as a raw_input. 因此,为避免该问题,我将方程式作为raw_input。
There is one way, eval
function.. eval
功能是一种方法。
>>> x = raw_input()
2 + 6
>>> x
'2 + 6'
>>> eval(x)
8
But be sure to verify that the input only has numbers,and symbols. 但是请确保验证输入中只有数字和符号。
>>> 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
doesn't work: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.