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

Question:

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?

Asked By: Deneb

||

Answers:

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

Answered By: RichieHindle

Because you read the whole document into one string that looks like:

'anbncndn'

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:

'anbncnd'

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

Answered By: Viktor Kerkez

Try this instead:

with open('doc.txt') as f:
    for line in f:
        print line,

Explanation:

  • The recommended way to open a file is using with, which takes care of closing the file at the end
  • You can iterate over each line in the file using for line in f
  • There’s no need to call rstrip() now, because we’re reading and printing one line at a time
Answered By: Óscar López

Consider using replace and replacing each instance of ‘n’ with ”. This would get rid of all the new line characters in the input text.

Answered By: Surveon

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.

Answered By: Martijn Pieters

i am also facing issue for r in command line while executing unix command thru python– channel.send(cmd) using paramiko

this need to be run — cmd =manage show OPER .oc.CSCORE alarm_object 27734183 all a
but its getting o/p–cmd = b’manage show OPER .oc.CSCORE alarm_object 27734183 al rl a’

i tried .rstrip() , replace(‘r’, ”), = ”.join(cmd)…
but no luck… any one can help.

Answered By: Basavraj R
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.