readlines给了我额外的换行符python2.6.5 [英] readlines gives me additional linebreaks python2.6.5
本文介绍了readlines给了我额外的换行符python2.6.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对以下代码有疑问:
file = open("file.txt", "r")
lines = file.readlines()
print lines[0]
print lines[1]
print lines[2]
file.close()
此代码使我在两行之间换行.所以输出是这样的:
This code gives me linebreaks between the lines. So the output is something like this:
line0
line1
line2
如何解决?
推荐答案
print
添加换行符.从该行中删除换行符:
print
adds a newline. Strip the newline from the line:
print lines[0].rstrip('\n')
print lines[1].rstrip('\n')
print lines[2].rstrip('\n')
If you are reading the whole file into a list anyway, an alternative would be to use str.splitlines()
:
lines = file.read().splitlines()
默认情况下会同时从行中删除换行符.
which by default removes the newlines from the lines at the same time.
这篇关于readlines给了我额外的换行符python2.6.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文