Removing "\ n" for each line except the last line

I currently have test.txt

1234 5678 

I want to print each line without a new line char "\ n"

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

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

+4
source share
2 answers

You can use str.rstrip

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

This will remove a new line from each line (if any). rstrip itself will remove all trailing spaces, not just newlines.

For instance:

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

Associated with str.strip , which is removed at both ends, and str.lstrip , which is removed only at the left.

+4
source

Use rstrip .

i.rstrip() will remove all spaces on the right, i.rstrip('\n') only newlines.

+4
source

All Articles