Ad

In Python Is It Possible To Split A List In First, Inner And Last Element In One Expression?

- 1 answer

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
Ad