Ad
In Python Is It Possible To Split A List In First, Inner And Last Element In One Expression?
Imagine a string s="one two three four five"
. I'd like to split it into it's first, last and the 'inner' element. I know I can do this with clever unpacking and re-joining:
first, *rest, last = s.split(" ")
middle = " ".join(rest)
print(first, middle, last)
Is it possible to do this in one expression? (i.e. maybe without splitting the whole string string first and re-joining it afterwards)
Ad
Answer
Doing it in 2 steps using split
and rsplit
is the most readable, sensible and fastest solution
first, rest = s.split(' ', 1)
middle, last = rest.rsplit(' ', 1)
But if you still think, you like to do in one step, you can do it using re.split
first, middle, last = re.split(r' +(.*) +', s)
Ad
source: stackoverflow.com
Related Questions
- → 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
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → 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
Ad