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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With