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.
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())
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With