Ad

How To Split A List By String

- 1 answer

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.

Ad

Answer

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']
Ad
source: stackoverflow.com
Ad