Python 为什么 .rstrip('\n') 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18281865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:23:13  来源:igfitidea点击:

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

pythonline

提问by Deneb

Let's say doc.txtcontains

假设doc.txt包含

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?

为什么我得到相同的值?

采纳答案by Martijn Pieters

str.rstrip()removes the trailingnewline, not all the newlines in the middle. You have one long string, after all.

str.rstrip()删除尾随的换行符,而不是中间的所有换行符。毕竟你有一根很长的绳子。

Use str.splitlines()to split your document into lines without newlines; you can rejoin it if you want to:

使用str.splitlines()您的文件分割成线不带换行; 如果你想,你可以重新加入它:

doclines = doc.splitlines()
doc_rejoined = ''.join(doclines)

but now doc_rejoinedwill have all lines running together without a delimiter.

但现在doc_rejoined所有行都将在没有分隔符的情况下一起运行。

回答by RichieHindle

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

rstrip从整个字符串中去除尾随空格。如果您希望它在单独的行上工作,则需要首先使用类似doc.split('\n').

回答by Viktor Kerkez

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 \nwill be removed, leaving all the other untouched, so the string would look like:

当你rstrip('\n')对该字符串执行 a时,只有最右边的\n会被删除,其他的都保持不变,所以字符串看起来像:

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

解决方案是将文件分成几行,然后右删除每一行。或者只是用空替换所有换行符:s.replace('\n', ''),这会给你'abcd'.

回答by óscar López

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
  • 推荐的打开文件的方法是使用with,它负责在最后关闭文件
  • 您可以使用 for line in f
  • rstrip()现在不需要打电话了,因为我们一次读取和打印一行

回答by Surveon

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

考虑使用替换并将 '\n' 的每个实例替换为 ''。这将消除输入文本中的所有换行符。