Print without a newline in Python

With python 3 you can override the print function’s delimiter value to make it null or whatever else you want. But if you’re stuck with 2.5 or 2.6 like the rest of us, you can still print without a newline using sys or print with a coma. Try this on for size:
12
import syssys.stdout.write("x")
|
1 2 |
import sys sys.stdout.write("x") |
The only problem with this is when you want to use it like a progress bar. If you do this in a loop over time, you will get the expected output, but over time it won’t be the way you expected.
12345 import os, time, syswhile not os.path.exists(path):time.sleep(1)sys.stdout.write(".")print("Finally there!")
What you might expect is a dot to appear once every second until the path does exist at which time “Finally there!” would append to the dot’s, ending with a newline character.
Wrong.
What you’ll actually find is no output at all until the loop exits. You’ll just pause for awhile, then all the dots and the printed message show up all at once. Hmm I guess stdout is buffered. So to fix this, just flush each time you want to make sure the display is updated.
123456 import os, time, syswhile not os.path.exists(path):time.sleep(1)sys.stdout.write(".")sys.stdout.flush()print("Finally there!")
………….Finally there!
Yet another way would be to use a coma at the end of a normal print function! I love & hate this method because it’s easily forgotten or overlooked when you’re looking at code later, but it is simpler and cleaner looking.
123456 #!/usr/bin/env pythonx = "derp"print("herp "),print(x),print "herpidy ",print x,
|
1 |
herp derp herpidy derp |
Why use ugly system calls when you don’t really need to, right?