gpt4 book ai didi

Is it possible to perform a mathematical operation based on a string input? [duplicate](可以基于字符串输入执行数学运算吗?[复制])

转载 作者:bug小助手 更新时间:2023-10-28 21:56:10 25 4
gpt4 key购买 nike




I just made a quick counter in Python where you just have to type in the following numbers, one by one (as some of you might have seen on some Discord servers)

我刚刚用Python语言做了一个快速计数器,你只需一个接一个地输入以下数字(就像你们中的一些人可能在一些不一致的服务器上看到的那样)


I wanted to make it more interesting by adding the possibility of typing mathematical operations in the input, so that if the next number is 3 you can type 2+1, but it didn't go well.

我想通过在输入中添加输入数学运算的可能性来使它更有趣,这样如果下一个数字是3,您可以输入2+1,但它并不顺利。


This is the original code:

这是原始代码:


contador = 0
operaciones = ["+","-","*","/"]

while True:
if contador == 0:
numero = int(input("¡Comenzamos! Estamos en 0: "))
if numero == contador + 1:
contador = numero
else:
print("¡Has perdido!")
break

numero = int(input("Introduce el siguiente número: "))
if numero == contador + 1:
contador = numero
else:
print("¡Has perdido!")
break

When running it, this is the error message I get:
invalid literal for int() with base 10: '2+1'

Then I tried changing the inputs to string instead of int, but it just wouldn't work.

当运行它时,这是我得到的错误消息:invalid literal for int()with base 10:'2+1'然后我尝试将输入改为string而不是int,但它就是不起作用。


更多回答

There is SimpleEval, a python module which was developed following a similar question on StackOverflow

有一个SimpleEval,这是一个在StackOverflow上出现类似问题后开发的Python模块

优秀答案推荐

The problem here is that you are trying to get the entire string as int - that is not possible, because you're not thinking about the operators.

这里的问题是,您试图将整个字符串作为int-这是不可能的,因为您没有考虑运算符。


This regex matches one or more digits (\d+) followed by one of the four basic math operators ([±/*]) followed by one or more digits (\d+).

此正则表达式匹配一个或多个数字(\d+),后跟四个基本数学运算符([±/*])中的一个,然后是一个或多个数字(\d+)。


import re
string = input("¡Comenzamos! Estamos en 0: ")
pattern = r"(\d+)([+-\/*])(\d+)"
match = re.match(pattern, string)
if match:
num1 = match.group(1) # "2"
op = match.group(2) # "+"
num2 = match.group(3) # "1"


A quick solution is use eval() as said by @pirosow, but please take care because in this way you may encounter dangerous inputs (code execution or exceptions due to bad inputs).

正如@pirosow所说,一种快速的解决方案是使用val(),但请小心,因为这样您可能会遇到危险的输入(代码执行或由于错误输入而导致的异常)。


In other words, I wont raccomend eval(). Take a look on librieries like pandas or sympy may be a more solid choice if you don't want to manually parse string inputs.

换句话说,我不推荐使用val()。如果您不想手动解析字符串输入,那么看看像PANDA或SIMNY这样的库可能是更可靠的选择。



You can use the eval() function:

您可以使用val()函数:


print(eval('2 + 1'))

will print 3!

将打印3!


Also, it works to convert strings to other types of variables!

此外,它还可以将字符串转换为其他类型的变量!


By the way, it can be very dangerous if you put a string of functions that can, for example, delete your files, so be careful.

顺便说一句,如果你放了一串函数,比如可以删除你的文件,这可能是非常危险的,所以要小心。


更多回答

The current documentation for literal_eval indicates that "safe" is not entirely true. While it won't evaluate python code like eval will, it still can be dangerous to run on untrusted input.

当前的文件表明,“Safe”并不完全正确。虽然它不会像val will那样计算python代码,但在不可信的输入上运行仍然是危险的。

Yes you're right. I edited the sentence to not make it sound like its 100% safe.

是的,你说得对。我编辑了这句话,不让它听起来像是100%安全的。

I got ValueError: malformed node or string on line 1: <ast.BinOp object at 0x...> using ast.literal_eval('2+1'), didn't you?

我在第1行得到了ValueError:格式错误的节点或字符串:,是不是使用ast.wen al_val(‘2+1’)?

Never suggest eval without mentioning that this might be the most dangerous function in Python. Please read: Eval really is dangerous

千万不要在不提到这可能是Python中最危险的函数的情况下建议val。请阅读:伊瓦尔真的很危险

You can use the pure-eval library for a safer alternative.

您可以使用纯评价库作为更安全的替代方案。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com