I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
for item in range(1,100):
print item
The result is:
1
2
3
4
.
.
.
How get this to instead look like:
1 2 3 4 5 ...
Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time?
You can add a trailing comma to your print statement to print a space instead of a newline in each iteration:
Alternatively, if you're using Python 2.6 or later, you can use the new print function, which would allow you to specify that not even a space should come at the end of each item being printed (or allow you to specify whatever end you want):
Finally, you can write directly to standard output by importing it from the sys module, which returns a file-like object:
The best way to accomplish this is to use the
\r
characterJust try the below code:
In Python 3 you can do it this way:
Outputs:
Tuple: You can do the same thing with a tuple:
Outputs:
Another example:
Outputs:
You can even unpack your tuple like this:
Outputs:
another variation:
Outputs:
For Python(2.7)
Python 3
Use
print item,
to make the print statement omit the newline.In Python 3, it's
print(item, end=" ")
.If you want every number to display in the same place, use for example (Python 2.7):
In Python 3, it's a bit more complicated; here you need to flush
sys.stdout
or it won't print anything until after the loop has finished: