在循环内打印时输出中的额外行

fin*_*pin 11 python

我无法弄清楚为什么代码#1返回一个额外的空行而代码#2没有.有人可以解释一下吗?区别在于代码#2末尾的额外逗号.

# Code #1
file = open('tasks.txt')

for i, text in enumerate(filer, start=1):
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text)

# Code #2
file = open('tasks.txt')

for i, text in enumerate(filer, start=1):
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text),
Run Code Online (Sandbox Code Playgroud)

这是我的tasks.txt文件的内容:

line 1
line 2
line 3
line 4
line 5
Run Code Online (Sandbox Code Playgroud)

代码#1的结果:

(2) line 2

(3) line 3

(4) line 4
Run Code Online (Sandbox Code Playgroud)

代码#2的结果(期望的结果):

(2) line 2
(3) line 3
(4) line 4
Run Code Online (Sandbox Code Playgroud)

Lev*_*von 16

,print语句中的尾部将压缩换行符.您的第一个打印声明没有,第二个打印声明没有.

您读取的输入仍包含\n导致额外换行的输入.补偿它的一种方法是通过使用尾随逗号来防止打印发出自己的换行符.或者,可以说是更好的方法,你可以在阅读时删除输入中的换行符(例如,通过使用rstrip())

  • `, end=''` 与 python 3 (3认同)

Joh*_*hin 5

对这个问题最好的一般答案是在您阅读后立即删除尾随的换行符(如果有的话!):

f = open('tasks.txt')
for i, text in enumerate(f, start=1):
    text = text.rstrip('\n')
    if i >= 2 and i <= 4:
        print "(%d) %s" % (i, text)
Run Code Online (Sandbox Code Playgroud)

这样您就可以将输出与输入分离……您的输出代码可能相距 20 行,或者在不同的函数/方法中,甚至在不同的模块中。通过在打印语句末尾使用逗号来补偿输入中的换行符并不是一个可靠的解决方案。