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.

  1.  
  2. import sys
  3. for i in range (10):
  4. sys.stdout.write ( "%d.." % i )
  5.  

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

  1.  
  2. print 1,2,3, "Hi"
  3.  

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

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

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 🙂

  1. No Comments



css.php