我对Python很陌生,我正在尝试创建某种计算器,它将表达式读入字符串并计算它们(不带eval)。为了做到这一点,在将字符串转换为由括号、运算符和值分隔的列表之后,我正在处理一个列表。我也有一个包含操作符的列表,我只是不知道如何在regex拆分中使用它,所以直到现在我才手动完成这个操作。
我的代码有三个问题:
_作为一个新运算符添加,代码将不知道按照它进行拆分)。 # 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] -> I当前获得:['5', '-', '-', '5']
另一个例子:我想要得到的((500-4)*-3) ->:['(', '(', 500, '-', '4', ')', *', '-3', ')']
发布于 2019-12-21 12:31:26
这里有一段路要走:
import re
arr = [
'5--5',
'((500-4)*-3)',
]
for s in arr:
res = re.findall(r'\b-\b|-?\d+|\D', s)
print res输出:
['5', '-', '-5']
['(', '(', '500', '-', '4', ')', '*', '-3', ')']https://stackoverflow.com/questions/59435628
复制相似问题