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')
But the new output has a bunch of escape characters (the "\" symbol). I tried replacing them with:
But that didn't work either.
I'm thinking there has to be a simple way to do this that I'm missing.
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']
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module