Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string using a list of value at the same time

I have a string and a list:

src = 'ways to learn are read and execute.'
temp = ['ways to','are','and']

What I wanted is to split the string using the list temp's values and produce:

['learn','read','execute']

at the same time.

I had tried for loop:

for x in temp:
    src.split(x)

This is what it produced:

['','to learn are read and execute.']
['ways to learn','read and execute.']
['ways to learn are read','execute.']

What I wanted is to output all the values in list first, then use it split the string.

Did anyone has solutions?

like image 509
RexLeong Avatar asked Mar 07 '26 12:03

RexLeong


1 Answers

re.split is the conventional solution for splitting on multiple separators:

import re

src = 'ways to learn are read and execute.'
temp = ['ways to','are','and']

pattern = "|".join(re.escape(item) for item in temp)
result = re.split(pattern, src)
print(result)

Result:

['', ' learn ', ' read ', ' execute.']

You can also filter out blank items and strip the spaces+punctuation with a simple list comprehension:

result = [item.strip(" .") for item in result if item]
print(result)

Result:

['learn', 'read', 'execute']
like image 188
Kevin Avatar answered Mar 09 '26 01:03

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!