Simple question: given a string
string = "Word1 Word2 Word3 ... WordN"
is there a pythonic way to do this?
firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]
Like an unpacking or something?
Thank you
Since Python 3 and PEP 3132, you can use extended unpacking.
This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable first, and the others will belong to the list (possibly empty) others.
first, *others = string.split()
Also, note that default delimiter for .split() is a space, so you do not need to specify it explicitly.
From Extended Iterable Unpacking.
Many algorithms require splitting a sequence in a "first, rest" pair, if you're using Python2.x, you need to try this:
seq = string.split()
first, rest = seq[0], seq[1:]
and it is replaced by the cleaner and probably more efficient in Python3.x:
first, *rest = seq
For more complex unpacking patterns, the new syntax looks even cleaner, and the clumsy index handling is not necessary anymore.
otherWords = string.split(" ")[1:], right? - THN