Extra line in output when printing inside a loop

后端 未结 5 548
鱼传尺愫
鱼传尺愫 2021-01-11 17:33

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

5条回答
  •  渐次进展
    2021-01-11 18:03

    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.

提交回复
热议问题