简体   繁体   English

如何在python中将str文字转换为int文字?

[英]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+3str更改为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.

相关问题 我如何区分 str 和 int 这就是 ValueError: invalid literal for int() with base 10: error 的意思吗? - how do I differentiate between str and int and is this what ValueError: invalid literal for int() with base 10: error means? 如何修复 ValueError:int() 的无效文字,基数为 10:''? - How do i fix ValueError: invalid literal for int() with base 10: ''? int()Python的文字无效 - Invalid literal for int() Python 如何在 python 中使用基数 2 修复 int() 的无效文字:''? - How to fix invalid literal for int() with base 2: ' ' in python? 我在带有字节文字的字符串上使用 str() ,如何反转操作? - I used str() on string with byte literal, how do I reverse the operation? Python 3:如何将递增文字放在循环中? - Python 3: How do I place an incrementing literal in a loop? 如何在Python中指定文字生成器类型? - How do I specify the literal generator type in Python? Python 3:如何获得字节字符串的字符串文字表示? - Python 3: How do I get a string literal representation of a byte string? 如何在 mysql 连接器 python 查询中获得文字“%”? - How do I get a literal '%' in a mysql connector python query? 如何在 python 中键入浮点无穷大文字 - How do I type a floating point infinity literal in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM