How to skip the extra newline while printing lines read from a file?

后端 未结 1 1192
既然无缘
既然无缘 2021-01-18 07:46

I am reading input for my python program from stdin (I have assigned a file object to stdin). The number of lines of input is not known beforehand. Sometimes the program mig

相关标签:
1条回答
  • 2021-01-18 07:49

    the python print statement adds a newline, but the original line already had a newline on it. You can suppress it by adding a comma at the end:

    print line , #<--- trailing comma
    

    For python3, (where print becomes a function), this looks like:

    print(line,end='') #rather than the default `print(line,end='\n')`.
    

    Alternatively, you can strip the newline off the end of the line before you print it:

    print line.rstrip('\n') # There are other options, e.g. line[:-1], ... 
    

    but I don't think that's nearly as pretty.

    0 讨论(0)
提交回复
热议问题