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
Why doesn't .rstrip('\n') work?
提问by Deneb
Let's say doc.txt
contains
假设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_rejoined
will have all lines running together without a delimiter.
但现在doc_rejoined
所有行都将在没有分隔符的情况下一起运行。
回答by RichieHindle
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')
.
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 \n
will 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()
现在不需要打电话了,因为我们一次读取和打印一行