Split a string with multiple delimiter & create a separate list

Advertisements

I have a python string that contains a list of words separated by either a plus or minus sign

s = "AA + BB + 1C - CC - DD"

I want to get a list of words with a plus sign which is below

plusList = ["AA", "BB", "1C"]

And a list with a minus sign as below

minusList = ["CC", "DD"]

Any help appreciated.
Thank you!

>Solution :

import re

s = "AA + BB + 1C - CC - DD"

plusList = re.findall(r"(?:^|\+\s*)(\w+)", s)
minusList = re.findall(r"(?:\-\s*)(\w+)", s)

print(plusList)
print(minusList)
<script src="https://cdn.jsdelivr.net/gh/pysnippet/pysnippet@latest/snippet.min.js"></script>

Leave a ReplyCancel reply