Printing on one line with Python

Ok so I’ve been using Python for a long time and have written a lot of lines of Python code. But this one is pretty simple and I’m kind of embarrassed that somehow I didn’t know about it.

In the past, I’ve used sys.stdout when I wanted to print multiple things on one line, e.g., you want to print periods to show progress.

import sys
for i in range (10):
 sys.stdout.write ( "%d.." % i )

I also knew you could use print with more than one item.

print 1,2,3, "Hi"

But the other day I inadvertently found that you can continue to print on one line if you just leave the trailing comma….

for i in range(10):
  print "%d.." % i, # no newline appended
print # add a newline after the loop.

And who cares you say??? Well now I don’t have to import sys and use sys.stdout when a simple print can do just fine 🙂

This entry was posted in Programming and tagged . Bookmark the permalink.