我需要在像这样的字符串中的子字符串(包含 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)
但是好像不行,代码只是返回原始消息的多个副本,并没有在句尾添加括号。我该怎么办?
如果您的字符串始终是由 OR 分隔的术语列表,则您可以拆分并加入:
>>> " OR ".join("({})".format(s.strip()) for s in message.split("OR"))
'(a and b amount) OR (c and d amount) OR (x and y amount)'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句