Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing the "\n" for every line except for the last line

Tags:

python

io

Currently I have a test.txt

1234
5678

I want to print out each line without the newline char "\n"

file=open("test.txt","r")
lines = file.readlines()
for i in lines:
    print i[:-1]

this will remove the \n for the first line, but for the second line: 5678, the 8 will be cut off because there is no \n after it. What is a good way to handle this correctly?

like image 659
PhoonOne Avatar asked Feb 17 '23 01:02

PhoonOne


2 Answers

You can use str.rstrip

for i in lines:
    print i.rstrip('\n')

This will remove the newline from each line (if there is one). rstrip on its own will remove all trailing whitespace, not just newlines.

For example:

>>> 'foobar\n'.rstrip('\n')
foobar
>>> 'foobar'.rstrip('\n')
foobar
>>> 'foobar  \t \n'.rstrip()
foobar

Related are str.strip, which strips from both ends, and str.lstrip, which strips from the left only.

like image 54
Volatility Avatar answered Feb 19 '23 19:02

Volatility


Use rstrip.

i.rstrip() will strip all whitespace from the right, i.rstrip('\n') just the newlines.

like image 40
Pavel Anossov Avatar answered Feb 19 '23 21:02

Pavel Anossov