Is it possible to split and assign a string in a single statement?

Slicing supports a step parameter

a = "Jack and Jill went up the hill"
(user1 , user2) = a.split()[0:4:2] #picks 1 and 3 element in the list

but while it's possible to write funky oneliners in Python for sure it's not the best language for that kind of exercise.


If you want to get fancy, you could use operator.itemgetter:

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values.

Example:

>>> from operator import itemgetter
>>> pick = itemgetter(0, 2)
>>> pick("Jack and Jill went up the hill".split())
('Jack', 'Jill')

Or as a one-liner (w/o the import):

>>> user1, user2 = itemgetter(0, 2)("Jack and Jill went up the hill".split())

This does the trick:

user1, user2 = a.split()[0::2][:2]

Pick the first two elements of the sequence counting from 2 in 2.


You can do something like this

a = "Jack and Jill went up the hill"
user1, _, user2, _ = a.split(" ", 3)

where _ means that we don't care of the value, and split(" ", 3) split the string in 4 segments.

Tags:

Python