如何在字符串中的子字符串周围添加括号?



我需要在字符串中的子字符串(包含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 ".join(map(lambda x: "({})".format(x), message.split(" OR ")))

或者,如果您想要更具可读性的版本

sentences = message.split(" OR ")
# apply parenthesis to every sentence
sentences_with_parenthesis = list(map(lambda x: "({})".format(x), sentences))
result = " OR ".join(sentences_with_parenthesis)

如果您的字符串始终是由 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)'

您可能只想将所有子句分解为一个列表,然后 用括号将它们重新连接起来。 像这样的东西,虽然它 即使没有 OR 子句,也要添加括号:

original = "a and b OR c and d OR e and f"
clauses = original.split(" OR ")
# ['a and b', 'c and d', 'e and f']
fixed = "(" + ") OR (".join(clauses) + ")"
# '(a and b) OR (c and d) OR (e and f)'

相关内容

  • 没有找到相关文章

最新更新