How can I add an if statement to a generator in Python?

this is my code:

s = ''.join('%s: %s </br>' % (a,getattr(user, a) ) for a in dir(user))

and I want to add ifto this code, so I write:

s = ''.join('%s: %s </br>' % (a,getattr(user, a) if !a.index('__') ) for a in dir(user))

I think it's wrong,

What is the correct way to add a iffor loop,

thank

+3
source share
2 answers

You want the condition to be evaluated at each iteration through the loop at the end, for example:

s = ''.join('%s: %s </br>' % 
               (a,getattr(user, a)) for a in dir(user) if '__' not in a
           )

Edit: Sorry, copy the brackets to the appropriate attachment.

Edited: Condition changed (didn’t even pay attention to it, thanks Falmarri.

+1
source

Syntax for iterated in interator if condition(iterated), so you need to move ifafter dir(user):

s = ''.join('%s: %s </br>'
        % (a,getattr(user, a) for a in dir(user) if !a.index('__') ))
0
source

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


All Articles