'Python Split a String but Keep The Matched String
Consider a string in a list that needs to be parsed.
Example
['Service Request',
'Please view this in here',
'Your Service:example Request Date and Time: 4/7/2022 8:20:54 PMService: Sub Service:']
Output (objective)
['Service Request',
'Please view this in here',
'Your Service:example',
'Request Date and Time: 4/7/2022 8:20:54 PM',
'Service: ',
'Sub Service:']
The issue is that if I use the code below, the matched string isn't included in the list. However, the goal is to preserve the matched string.
for idx, te in enumerate(text):
if any(x in te for x in matches_req):
text[idx] = re.split('Your Service:|Request Date and Time:|Service:|Sub Service:', te)
def flatten(lst):
for x in lst:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
text = list(flatten(text))
Output at the moment (wrong)
['Service Request',
'Please view this in here',
'example,
'4/7/2022 8:20:54 PM']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
