Extra line in output when printing inside a loop

后端 未结 5 551
鱼传尺愫
鱼传尺愫 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:04

    Iterating over files keeps the newlines from the file. So there's one newline from your print, and one from the string.

    A good way to test file semantics is with StringIO. Take a look:

    >>> from StringIO import StringIO
    >>> x = StringIO("abc\ncde\n")
    >>> for line in x: print repr(line)
    ... 
    'abc\n'
    'cde\n'
    

    The comma suppresses the newline from the print, as Levon says, so that there's only the newline from the string.

    I strip newlines from strings using s.rstrip('\n'). It gets rid of any trailing newlines in any modernish format (Unix, Windows, or old Mac OS). So you can do print "(%d) %s" % (i, text.rstrip('\n')) instead.

提交回复
热议问题