为什么.rstrip('\ n')不起作用? [英] Why doesn't .rstrip('\n') work?

查看:239
本文介绍了为什么.rstrip('\ n')不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设doc.txt包含

a
b
c
d

我的代码是

f = open('doc.txt')
doc = f.read()
doc = doc.rstrip('\n')
print doc

为什么我得到相同的值?

why do I get the same values?

推荐答案

str.rstrip()删除 trailing 换行符,而不是中间的所有换行符.毕竟,你有一长串.

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

使用 str.splitlines() 将您的文档分成几行没有换行符;您可以根据需要重新加入它:

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)

但是现在doc_rejoined将使所有行一起运行而没有定界符.

but now doc_rejoined will have all lines running together without a delimiter.

这篇关于为什么.rstrip('\ n')不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆