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
The best general answer to this problem is to strip the trailing newline (if any!) as soon as you read it:
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)
That way you uncouple your output from your input ... your output code may be 20 lines away or in a different function/method or even in a different module. Compensating for a newline in input by using a comma at the end of the print statement is not a robust solution.