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

社会主义新天地 提交于 2019-12-23 07:07:18

问题


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?


回答1:


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.




回答2:


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




回答3:


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




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/18281865/why-doesnt-rstrip-n-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!