What does this piece of code do, python

I am learning python myself and I was doing an exercise whose solution was posted in this thread. Can anyone translate into English what this piece of code means? When I found out what statements I never came across this syntax.

consonants = 'bcdfghjklmnpqrstvwxz' return ''.join(l + 'o' + l if l in consonants else l for l in s) 
+6
source share
2 answers

This is a longer piece of code written as a generator. This is how it will look more stretched.

 consonants = 'bcdfghjklmnpqrstvwxz' ls = [] for l in s: if l in consonants: ls.append(l + 'o' + l) else: ls.append(l) return ''.join(ls) 

It goes through s and checks if l in the consonants line. If so, it pushes l + 'o' + l to the list, and if not, then just press l .

Then the result is concatenated into a string using ''.join and returned.

More precisely (as a generator):

 consonants = 'bcdfghjklmnpqrstvwxz' def gencons(s): for l in s: if l in consonants: yield l + 'o' + l else: yield l return ''.join(gencons(s)) 

Where gencons is just an arbitrary name, I gave a generator function.

+11
source

This piece of code contains neither an if nor a for loop. You can say it most easily, because statements cannot be embedded in an expression, such as the one that is passed as the join argument.

 consonants = 'bcdfghjklmnpqrstvwxz' return ''.join(l + 'o' + l if l in consonants else l for l in s) 

if is part of a conditional expression that has the form x if y else z . Unlike the if , the else parameter is required, because the expression must be true or not. If y true, the value of x ; otherwise, the value of z . In this case, the value is either l + 'o' + l (when l is consonant) or l .

The for keyword is used to denote a generator expression, which you can think of as essentially a way to generate a sequence of values ​​based on another sequence. Here we start with some sequence s and create a different value for each of the characters l in this sequence. The resulting sequence is used by join to create a new line.

(A bit off topic, but it’s more efficient to explicitly pass the list, rather than the generator, to join , since it needs to first create a list to determine how much space is allocated for the resulting row.

 return ''.join([l + 'o' + l if l in consonants else l for l in s]) 

)

0
source

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


All Articles