Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list by string

I have several large lists of strings. I need to split all of those lists into two lists so that I keep only the 2nd list. For example:

lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']

I want to grab only the strings after 'split_here' so that the new list will be this:

new_lst = ['something else', 'we like cake', 'aardvarks']

I tried this:

new_list = str(lst).split('split_here')[1]

But the new output has a bunch of escape characters (the "\" symbol). I tried replacing them with:

.replace('\\', '')

But that didn't work either.

I'm thinking there has to be a simple way to do this that I'm missing.

like image 433
Ragnar Lothbrok Avatar asked Jun 30 '26 14:06

Ragnar Lothbrok


2 Answers

You're looking for list operations, not for string operations. We just need to find the position where the separator string appears, and take a slice starting from the next element, like this:

lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']
new_list = lst[lst.index('split_here')+1:]

The above assumes that the separator string is present in the list, otherwise we'll get a ValueError. The result is as expected:

new_list
=> ['something else', 'we like cake', 'aardvarks']
like image 151
Óscar López Avatar answered Jul 03 '26 04:07

Óscar López


Using list#index is probably the cleanest solution.

Still, since you were trying to find a solution with strings and split, you could use:

'#'.join(lst).split('split_here#')[-1].split('#')

Note that it only works if you're sure that # never appears in your strings.

Here are the steps shown in the console:

>>> lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']
>>> '#'.join(lst)
'This is a list#of strings#blahblahblah#split_here#something else#we like cake#aardvarks'
>>> '#'.join(lst).split('split_here#')
['This is a list#of strings#blahblahblah#', 'something else#we like cake#aardvarks']
>>> '#'.join(lst).split('split_here#')[-1]
'something else#we like cake#aardvarks'
>>> '#'.join(lst).split('split_here#')[-1].split('#')
['something else', 'we like cake', 'aardvarks']
like image 23
Eric Duminil Avatar answered Jul 03 '26 04:07

Eric Duminil