removing the "\n" for every line except for the last line
io, python
Solution
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.
Problem
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?