Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Can a string be split and some of the words be assigned to a tuple?

For instance:

a = "Jack and Jill went up the hill"
(user1, user2) = a.split().pick(1,3) # picks 1 and 3 element in the list.

Is such a one liner possible? If so what is the syntax.

like image 437
sheki Avatar asked Nov 30 '11 19:11

sheki


3 Answers

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())
like image 164
miku Avatar answered Oct 22 '22 00:10

miku


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.

like image 22
Cédric Julien Avatar answered Oct 21 '22 23:10

Cédric Julien


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.

like image 31
6502 Avatar answered Oct 22 '22 01:10

6502