假设 doc.txt
包含
a
b
c
d
我的代码是
f = open('doc.txt')
doc = f.read()
doc = doc.rstrip('\n')
print doc
为什么我得到相同的值?
最佳答案
str.rstrip()
删除尾随 换行符,而不是中间的所有换行符。毕竟你有一根长绳子。
使用str.splitlines()
将您的文档分成几行没有换行符;如果您愿意,可以重新加入:
doclines = doc.splitlines()
doc_rejoined = ''.join(doclines)
但现在 doc_rejoined
将所有行放在一起,没有分隔符。
关于python - 为什么 .rstrip ('\n' ) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281865/