Frage

foo = open('words.txt').readlines()
[k.rstrip() for k in foo if k.rstrip() != '']

I would like to reuse the modified key, like that

[k.rstrip() for k in foo if k != '']

Is this possible?


# input (words.txt)
# this will be just some lines with one or more words separated by space. 
# there will be no *special* case or anything 
foo bar  
baz  
bar baz waz

# expected output
>>> ['foo bar', 'baz', 'bar baz waz']
War es hilfreich?

Lösung

Do it like this:

[x for x in (k.replace('\n', '').strip() for k in foo) if x]

It looks like you want to filter out empty lines, you can do something like this for that:

#Assuming `c` is the file object
>>> [line.rstrip() for line in c if not line.isspace()]
['foo bar', 'baz', 'bar baz waz']
#Demo
>>> foo = ['foo bar\n', 'baz\n', 'bar baz waz\n', '   \n']
>>> [line.strip() for line in foo if not line.isspace()]
['foo bar', 'baz', 'bar baz waz']
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top