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

时间:2018-10-20 01:14:00

标签: python string shlex

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

但是它似乎不起作用,该代码仅返回原始消息的多个副本,并且没有在句子的末尾添加括号。我该怎么办?

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可能想将所有子句分成一个列表,然后 用括号将它们加入备份。像这样的东西 即使没有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)'