Skip to content Skip to sidebar Skip to footer

How To Skip The Extra Newline While Printing Lines Read From A File?

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 might get

Solution 1:

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.

Post a Comment for "How To Skip The Extra Newline While Printing Lines Read From A File?"