Ragnar Lothbrok
Ragnar Lothbrok

Reputation: 1145

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.

Upvotes: 3

Views: 3011

Answers (3)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

Adding to Oscar answer, You can use itertools.dropwhile() too:

from itertools import dropwhile

lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']
new_list = list(dropwhile(lambda x: x != 'split_here',lst))[1:]

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54303

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']

Upvotes: 2

Óscar López
Óscar López

Reputation: 236140

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']

Upvotes: 9

Related Questions