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?
The rstrip() method returns a copy of a string with the trailing characters removed. The rstrip() method has one optional argument chars . The chars argument is a string that specifies a set of characters which the rstrip() method will remove from the copy of the str .
The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n. Here are examples for Mac, Windows, and Unix EOL characters. Using '\r\n' as the parameter to rstrip means that it will strip out any trailing combination of '\r' or '\n'.
Remove \n From the String in Python Using the str. strip() Method. In order to remove \n from the string using the str. strip() method, we need to pass \n and \t to the method, and it will return the copy of the original string after removing \n and \t from the string.
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'
.
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