Skip to content Skip to sidebar Skip to footer

Avoiding Duplicate Function Call In List Comprehension In Python

I would like to iterate through each a file, trim the whitespace for each line, and delete the line if the returned string is empty. Is there a way to avoid duplicating the .strip

Solution 1:

You can use a nested list comprehension (well, generator expression in this case to avoid actually building a list):

newlns = [i + "\n" for i in (line.strip() for ln in lns) if i]

In fact you really shouldn't even bother to read the file first, just put it in there too: iterating over a file yields its lines.

withopen(fname, 'r') as file:
    newlns = [i + "\n"for i in (line.strip() for ln in file) if i]

Post a Comment for "Avoiding Duplicate Function Call In List Comprehension In Python"