'How to split sentence in a list based on two words?
I have a list of string like this lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin'], and I would like to split the words in list if they have and or with as separators such that the final outcome is ['John Kim', 'Kerry Lin', 'John Cena', 'Kim Rai', 'Kaster Baldwin']. How do I achieve this? My try was:
to_ret = []
for words in lst:
splitted = words.split(' and')
to_ret.extend(splitted)
new_ret = []
for words in to_ret:
splitted = words.split(' with')
new_ret.extend(splitted)
but this looks very repetitive. Any suggestions for cleaner code?
Solution 1:[1]
#my interpretation would be
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
toSplitWith= ["and" , "with"]
ans=[]
for word in lst:
for sprt in toSplitWith:
if sprt in word:
ans.extend(word.split(sprt))
print(ans)
Solution 2:[2]
you can do like this if you like: -
lst = ['John Kim and Kerry Lin', 'John Cena', 'Kim Rai with Kaster Baldwin']
to_ret = []
for i,word in enumerate(lst):
splittedand = word.split(' and')
splittedwith = word.split(' with')
to_ret.extend(splittedand)
to_ret.extend(splittedwith)
to_ret.remove(word)
print(to_ret)
out:
['John Kim', ' Kerry Lin', 'John Cena', 'Kim Rai', ' Kaster Baldwin']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | temo adeishvili |
| Solution 2 |
