Search code examples
pythonstringshlex

How to add parenthesis around a substring in a string?


I need to add parenthesis around a substring (containing the OR boolean operator) within a string like this:

message = "a and b amount OR c and d amount OR x and y amount"

I need to arrive at this:

message = "(a and b amount) OR (c and d amount) OR (x and y amount)"

I tried this code:

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)

But it does not seem to work, the code just returns multiple copies of the original message and doesn't add parenthesis at the end of the sentence. What do I do?


Solution

  • If your string always is a list of terms separated by ORs, you can just split and join:

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