Extra line in output when printing inside a loop

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

    There is a very simple fix for this.

    Let's say I have, for arguments sake, a .txt file (called numbers.txt) which I am reading from with the values:

    234234
    777776
    768768
    

    Then, using the following code:

    filename = numbers.txt
    
    with open(filename) as file_object:
        for line in file_object:
            print(line)
    

    Would give you the extra blank line as you are having problems with. But with a small change, you can get rid of the extra blank lines using the rstrip() method. So the code becomes:

    filename = numbers.txt
    
    with open(filename) as file_object:
        for line in file_object:
            print(line.rstrip())
    

    Now you will get your results without those annoying blank lines between them!

提交回复
热议问题