我需要在这样的字符串中的子字符串(包含 OR 布尔运算符)周围添加括号:
message = "a and b amount OR c and d amount OR x and y amount"
我需要达到这个:
message = "(a and b amount) OR (c and d amount) OR (x and y amount)"
我试过这段代码:
import shlex
message = "a and b amount OR c and d amount OR x and y amount"
target_list = []
#PROCESS THE MESSAGE.
target_list.append(message[0:message.index("OR")])
args = shlex.split(message)
attribute = ['OR', 'and']
var_type = ['str', 'desc']
for attr, var in zip(attribute, var_type):
for word in args:
if word == attr and var == 'str': target_list.append(word+' "')
else: target_list.append(word)
print(target_list)
但这似乎不起作用,代码只是返回原始消息的多个副本,并且没有在句尾添加括号。我该怎么办?