Python list understands invalid syntax while if statement

I have a list like this z = ['aaaaaa','bbbbbbbbbb','cccccccc']

, I would like to strip the first 6 characters from all elements, and if the element is empty, so as not to be placed in another list. So I made this code:

[x[6:] if x[6:] is not '' else pass for x in z]

I tried with

pass

continue

and still a syntax error. Maybe someone can help me? thank

+3


source to share


2 answers


Whenever you need to filter items from a list, this condition should be at the end. So you need to filter out empty items like

[x[6:] for x in z if x[6:] != ""]
# ['bbbb', 'cc']

      

Since the empty string is false, we can write the same condition succinctly as follows



[x[6:] for x in z if x[6:]]

      

Alternatively, as tobias_k suggested, you can check the length of the string like this

[x[6:] for x in z if len(x) > 6]

      

+9


source


If you are learning how to do lambda (not an official link) you should try with a map and filter like this:

filter(None, map(lambda y: y[6:], x))

      

Here the mapping (lambda y: y [6:], x) will only contain 7th character strings and replace other smaller strings with the logical "False". To remove all of these "False" values ​​from the new list, we will use the filter function.

You can only use this for educational purposes, as it is completely ugly when considering Python PEP8 . Understanding lists is the way to go as above.

[y[6:] for y in x if y[6:]]

      



Or traditional for a loop like

output = []
for y in x:
    if isinstance(y, str) and y[6:]:
        output.append(y[6:])

      

Note that even if the traditional way looks bigger, it can add more values ​​(for example, here, taking only strings from the list, if there are other data types in the list like lists, tuples, dictionaries, etc.)

So I would suggest either sticking with lists for simple managed lists, or the traditional way for controlled output

+1


source







All Articles