I can’t figure out why the code #1 returns an extra empty line while code #2 doesn’t. Could somebody explain this? The difference is an extra comma at the end of the code #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),
Here is the content of my tasks.txt file:
line 1
line 2
line 3
line 4
line 5
Result from code #1:
(2) line 2
(3) line 3
(4) line 4
Result from code #2 (desired result):
(2) line 2
(3) line 3
(4) line 4
The trailing
,in the print statement will surpress a line feed. Your first print statement doesn’t have one, your second one does.The input you read still contains the
\nwhich causes the extra linefeed. One way to compensate for it is to prevent print from issuing a linefeed of its own by using the trailing comma. Alternatively, and arguably a better approach, you could strip the newline in the input when you read it (e.g., by usingrstrip())