Home > database >  Split a string with multiple delimiter & create a separate list
Split a string with multiple delimiter & create a separate list

Time:07-02

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!

CodePudding user response:

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>

  • Related