Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解列由整数和基元组成的方程_Python_String_Integer_Primitive - Fatal编程技术网

Python 解列由整数和基元组成的方程

Python 解列由整数和基元组成的方程,python,string,integer,primitive,Python,String,Integer,Primitive,输入: 预期产出: 1st integer given: 3, 2nd integer given: 2, Primitives given in a STRING: '+' 因为3+2=5 我的做法: 5 正如预期的那样,我将得到ValueError:以10为基数的int()的无效文本:“3+2” 你知道我该怎么做吗?我必须使用所有给定的输入,这意味着我必须使用字符串(+)中的原语 谢谢 您可以使用eval str(3)+ '+' + str(2) --> '3+2' int(

输入:

预期产出:

1st integer given: 3, 
2nd integer given: 2, 
Primitives given in a STRING: '+'
因为3+2=5

我的做法:

5
正如预期的那样,我将得到ValueError:以10为基数的int()的无效文本:“3+2”

你知道我该怎么做吗?我必须使用所有给定的输入,这意味着我必须使用字符串(+)中的原语

谢谢

您可以使用eval

str(3)+ '+' + str(2)  --> '3+2'
int('3+2') --> Wishfully thinking: 5
你甚至可以用这个

eval( str(2) + '+' + str(3) )
或者,如果要分隔这些值:

print( eval( input( "insert equation: " )))
你可以使用eval

str(3)+ '+' + str(2)  --> '3+2'
int('3+2') --> Wishfully thinking: 5
你甚至可以用这个

eval( str(2) + '+' + str(3) )
或者,如果要分隔这些值:

print( eval( input( "insert equation: " )))

此函数递归调用自身,每次分解一个组件。 它也遵循标准


此函数递归调用自身,每次分解一个组件。 它也遵循标准

使用:

运行方式为:

first = raw_input('1st integer given: ')
second = raw_input('2nd integer given: ')
primitives = raw_input('Primitives given in a STRING: ')

equation = first+primitives+second
answer = eval(equation)
print answer
1st integer given: 3
2nd integer given: 2
Primitives given in a STRING: +
5
或:

first = raw_input('1st integer given: ')
second = raw_input('2nd integer given: ')
primitives = raw_input('Primitives given in a STRING: ')

equation = first+primitives+second
answer = eval(equation)
print answer
1st integer given: 3
2nd integer given: 2
Primitives given in a STRING: +
5
使用:

运行方式为:

first = raw_input('1st integer given: ')
second = raw_input('2nd integer given: ')
primitives = raw_input('Primitives given in a STRING: ')

equation = first+primitives+second
answer = eval(equation)
print answer
1st integer given: 3
2nd integer given: 2
Primitives given in a STRING: +
5
或:

first = raw_input('1st integer given: ')
second = raw_input('2nd integer given: ')
primitives = raw_input('Primitives given in a STRING: ')

equation = first+primitives+second
answer = eval(equation)
print answer
1st integer given: 3
2nd integer given: 2
Primitives given in a STRING: +
5

你可以用
ast.literal_eval('3+2')==5
Hi@minitech,在尝试您的方法时,我得到了一个
格式错误的字符串。有什么建议吗?@sgmart:你是怎么用的?就像你展示的那样。Python 2。7@sgmart:这是Python 3的东西。你可以使用
ast.literal_eval('3+2')==5
Hi@minitech,在尝试您的方法时,我得到了一个
格式错误的字符串。有什么建议吗?@sgmart:你是怎么用的?就像你展示的那样。Python 2。7@sgmart:这是一个Python 3的东西。