This question already has answers here:
Evaluating a mathematical expression in a string
                                
                                    (11个答案)
                                
                        
                                2年前关闭。
            
                    
因此,我知道如何将基本字符串转换为整数,但是如何将减法字符串(或任何其他数学函数)转换为整数?这不起作用:

str_a = '10-5'
b = 3
c = int(str_a) + b
ValueError: invalid literal for int() with base 10: '10-5'


那么我怎样才能使其正常工作呢? c必须等于8。

最佳答案

您可以使用ast.literal_eval()来评估str_a,如下所示:

import ast

str_a = '10-5'
c = ast.literal_eval(str_a) + 3
print(c)
str_a = '10+5-2' # you can use any operation not just subtraction and you can add as many numbers as you want
c = ast.literal_eval(str_a) + 2
print(c)


输出:

8
15

关于python - 如何在Python中将数字减法字符串转换为整数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46026670/

10-12 00:22
查看更多