DEV Community

Discussion on: 10 Awesome Pythonic One-Liners Explained

Collapse
 
devmount profile image
Andreas

Thank you for this addition. In this example I just wanted to strip both ends. To only remove the linebreaks, you have to specify the linebreak character:

c = [line.rstrip('\n') for line in open('file.txt')]
Collapse
 
anharrington profile image
Andrew N. Harrington

If you know the last line of the file does have a '\n', then line[:-1] is shorter.

Thread Thread
 
devmount profile image
Andreas

Indeed, thank you!

Thread Thread
 
paddy3118 profile image
Paddy3118

That's a big if. rstrip('\n') or simple rstrip() i find easier to read and less error prone.