我是新手,想用Python创建一个计算器,通过读取字符串表达式并计算它们来实现(不使用eval)。为此,我将字符串转换为由括号、运算符和值分隔的列表,然后使用列表进行操作。我有一个包含运算符的列表,但我不知道如何在正则表达式中使用它进行分割,因此到目前为止,我都是手动进行操作。
我的代码有3个问题: 1. 代码无法正确分割负数。 2. 代码无法添加运算符(例如,如果我想在未来添加“_”作为新运算符,则代码将无法根据它进行分割)。 3. 代码返回数字字符串,我需要在外部函数中将其转换为整数。
例如:
我的代码有3个问题: 1. 代码无法正确分割负数。 2. 代码无法添加运算符(例如,如果我想在未来添加“_”作为新运算符,则代码将无法根据它进行分割)。 3. 代码返回数字字符串,我需要在外部函数中将其转换为整数。
# Removing any unwanted white spaces, tabs, or new lines from the equation string:
equation = re.sub(r"[\n\t\s]*", "", equation)
# Creating a list based on the equation string:
result_list = re.split(r'([-+*/^~%!@$&()])|\s+', equation)
# Filtering the list - Removing all the unwanted "spaces" from the list:
result_list = [value for value in result_list if value not in ['', ' ', '\t']]
例如:
5--5
-> 我希望得到: [5, '-', -5]
-> 目前我得到的是: ['5', '-', '-', '5']
另一个例子: ((500-4)*-3)
-> 我希望得到:['(', '(', 500, '-', '4', ')', *', '-3', ')']
+
,-
)前面跟随数字时拆分来处理它们,即使用正向后查找(?<=\d)
来限定拆分。 - Nick