Let's say doc.txt
contains
a
b
c
d
and that my code is
f = open('doc.txt')
doc = f.read()
doc = doc.rstrip('\n')
print doc
why do I get the same values?
str.rstrip()
removes the trailing newline, not all the newlines in the middle. You have one long string, after all.
Use str.splitlines()
to split your document into lines without newlines ; you can rejoin it if you want to:
doclines = doc.splitlines()
doc_rejoined = ''.join(doclines)
but now doc_rejoined
will have all lines running together without a delimiter.
Because you read the whole document into one string that looks like:
'a\nb\nc\nd\n'
When you do a rstrip('\\n')
on that string, only the rightmost \\n
will be removed, leaving all the other untouched, so the string would look like:
'a\nb\nc\nd'
The solution would be to split the file into lines and then right strip every line. Or just replace all the newline characters with nothing: s.replace('\\n', '')
, which gives you 'abcd'
.
rstrip
strips trailing spaces from the whole string. If you were expecting it to work on individual lines, you'd need to split the string into lines first using something like doc.split('\\n')
.
Try this instead:
with open('doc.txt') as f:
for line in f:
print line,
Explanation:
with
, which takes care of closing the file at the end for line in f
rstrip()
now, because we're reading and printing one line at a time Consider using replace and replacing each instance of '\\n' with ''. This would get rid of all the new line characters in the input text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.