[英]How do I change a str literal into a int literal in python?
I want to make a program in which the user types a function ("3*x+3", for example) and the program obtains the Y
value from a specific x
value. 我想制作一个程序,其中用户键入一个函数(例如“ 3 * x + 3”),并且该程序从特定的
x
值获取Y
值。
The idea is that after the user types "3*x+3", the program replaces x
for 3, and prints the value of Y
, which in this case is 12. 这个想法是,在用户键入“ 3 * x + 3”之后,程序将
x
替换为3,并输出Y
的值,在这种情况下为12。
This is the code I have made: 这是我编写的代码:
K=raw_input()
x=3
result = int(K)
print (result)
When I execute the program and write The function, an error appears: 当我执行程序并编写函数时,出现错误:
ValueError: invalid literal for int() with base 10: '3*x+3'
ValueError:以10为底的int()的无效文字:'3 * x + 3'
This only happens when I type an expression with variables (even if they are previously defined). 仅当我键入带有变量的表达式(即使它们先前已定义)时,才会发生这种情况。 I think "int()" only works with str literals with only numbers, but I need it to work with numbers and variables (defined of course).
我认为“ int()”仅适用于仅具有数字的str文字,但是我需要它用于数字和变量(当然是定义的)。
What should I use instead of of int()
to change 3*x+3
from str
to a int
? 我应该使用什么代替
int()
将3*x+3
从str
更改为int
?
If you don't mind an additional dependency you can use numexpr (a third party module, not exactly lightweight but supports a lot of options) and its evaluate
function that does exactly what you need: 如果您不介意其他依赖项,则可以使用numexpr (第三方模块,不完全是轻量级的,但支持很多选项)及其
evaluate
函数完全可以满足您的需要:
import numexpr
x = 3
K = "3*x+3"
result = numexpr.evaluate(K).item()
print(result) # 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.