Reputation:
I have a list of strings:
List = ['aaa', 'bbb ccc', 'ddd (eee)']
I want to split elements that have parantheses either at the blank before the "(" or at the "(" in case that there is no blank ahead. But in this case, I want to keep the parantheses. So far I have come up with the following code that works if there is a blank:
for l in List:
if re.search('\(', l) != None:
a,b = re.split(' (?=\()', l)
print('True')
List_2.append(a)
List_2.append(b)
else:
List_2.append(l)
print(List_2)
Two Questions: First, is there a cleaner version of this, maybe using list comprehension. Second, how do I capture a case without a blank 'fff(ggg)'.
The final list should then look like this:
List_correct['aaa', 'bbb ccc', 'ddd', '(eee)', 'fff', '(ggg)']
Upvotes: 0
Views: 70
Reputation: 71689
Code:
List = ['aaa', 'bbb ccc', 'ddd (eee)', 'fff(ggg)']
result = [subitem for item in List for subitem in re.split(r"(?:\b|\s)(?=\()", item)]
Output:
>>>print(result)
['aaa', 'bbb ccc', 'ddd', '(eee)', 'fff', '(ggg)']
Upvotes: 3