Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't .rstrip('\n') work?

Tags:

python

line

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?

like image 635
Deneb Avatar asked Aug 16 '13 20:08

Deneb


People also ask

What does Rstrip \n do in Python?

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 .

Does Rstrip remove \n?

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'.

How do you strip n from a string in Python?

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.


2 Answers

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.

like image 119
Martijn Pieters Avatar answered Oct 07 '22 18:10

Martijn Pieters


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'.

like image 22
Viktor Kerkez Avatar answered Oct 07 '22 17:10

Viktor Kerkez