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

How to add parenthesis around a substring in a string?

我需要在这样的字符串中的子字符串(包含 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)

但是好像不行,代码只是returns多份原邮件,并没有在句末加括号。我该怎么办?

一些字符串操作函数应该可以在不涉及外部库的情况下实现这一目的

" 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)'