Pythonic way to split a string and unpack into variables?
Since Python 3 and PEP 3132 , you can use advanced unpacking.
Thus, you can unpack an arbitrary string containing any number of words. The first one will be stored in a variable first
, and the rest will belong to the list (possibly empty) others
.
first, *others = string.split()
Also note that the default separator for .split()
is space, so you don't need to specify it explicitly.
source to share
From Extended Unpacking Iterable .
Many algorithms require splitting the sequence into a "first, rest" pair, if you are using Python2.x you need to try the following:
seq = string.split()
first, rest = seq[0], seq[1:]
and it is being replaced by a cleaner and is probably more efficient in Python3.x
:
first, *rest = seq
For more complex unpacking templates, the new syntax looks even cleaner, and clumsy index handling is no longer necessary.
source to share