0

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?

Code Monkey
  • 800
  • 1
  • 9
  • 27

3 Answers3

1

A few string manipulation functions should do the trick without involving external libraries

" OR ".join(map(lambda x: "({})".format(x), message.split(" OR ")))

or, if you want a more readable version

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)
Marco
  • 141
  • 1
  • 4
0

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)'
orlp
  • 112,504
  • 36
  • 218
  • 315
0

You might want to just break all the clauses into a list and then join them back up with parenthesis. Something like this, though it adds parenthesis even with no OR clause:

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)'
Charles Merriam
  • 19,908
  • 6
  • 73
  • 83