Is it possible to split and assign a string in one expression?

Is it possible to break a line and assign some words 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 liner possible? If so, what is the syntax.

+8
source share
7 answers

If you want a fantasy, you can use operator.itemgetter :

Returns a called object that retrieves an element from its operand using the __getitem__() operand method. If multiple elements are specified, returns a tuple of search values.

Example:

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

Or as a single line (no import):

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

You can do something like this

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

where _ means that we do not care about the value, and split(" ", 3) divide the string into 4 segments.

+9
source

I would prefer to do this in two lines, but here is single-line:

user1, user2 = [token for (i, token) in enumerate(a.split()) if i in (0, 2)]

Here is what I would do instead (just for readability and less likely to introduce errors if they need to be changed in the future).

 tokens = a.split() user1 = tokens[0] user2 = tokens[2] 
+2
source

Slicing supports 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, this is certainly not the best language for this kind of exercise.

+2
source

This is the trick:

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

Select the first two elements of the sequence, counting from 2 to 2.

+2
source

The first thing that comes to my mind:

 >>> a = "Jack and Jill went up the hill" >>> [e for n, e in enumerate(a.split()) if n in (0, 2)] ['Jack', 'Jill'] 

In case you are curious: enumerate generates tuples with a progressive number as the first element and an enumerable iterable element as the second.

EDIT: As @kindall comments said, the final step would be:

 >>> user1, user2 = [e for n, e in enumerate(a.split()) if n in (0, 2)] >>> user1 'Jack' >>> user2 'Jill' 

but I decided not to complete the task, just to give an example as an example (sorry if this confused someone).

+1
source

Starting with Python 3.8 and introducing assignment expressions (PEP 572) ( := operator), we can first name the expression text.split() , then use its parts on the same line and create a (user1, user2) tuple:

 # text = 'Jack and Jill went up the hill' _, (user1, user2) = (parts := text.split()), (parts[0], parts[2]) # (user1, user2) = ('Jack', 'Jill') 
0
source

Source: https://habr.com/ru/post/902782/


All Articles