Pythonic way to split a string and unpack into variables?

Simple question: given the line

string = "Word1 Word2 Word3 ... WordN"

      

is there a pythonic way to do this?

firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]

      

How unboxing or something else?

thank

+3


source to share


2 answers


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.

+5


source


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.

+5


source







All Articles