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?
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.
Use rstrip
.
i.rstrip()
will strip all whitespace from the right, i.rstrip('\n')
just the newlines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With