Print without a newline in Python


blue-chart-green-arrow-125x125

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:

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.

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.

………….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.

Why use ugly system calls when you don’t really need to, right?


Posted on February 24th, by admica in programming, python.


Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">