Print New Output on Same Line

Print new output on same line

From help(print):

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.

You can use the end keyword:

>>> for i in range(1, 11):
... print(i, end='')
...
12345678910>>>

Note that you'll have to print() the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10 instead.

Print to the same line and not a new line?

It's called the carriage return, or \r

Use

print i/len(some_list)*100," percent complete         \r",

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

Python print to same line during loop

By default, terminal output won't appear until a newline is printed.

You can force partial lines to appear immediately by adding flush=True to the print call.

Print in one line dynamically

Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3

How to print 2 items on the same line

Separate the values with a comma:

print 'Your new balance:', new

See a demonstration below:

>>> new = 123
>>> print 'Your new balance:', new
Your new balance: 123
>>>
>>> print 'a', 'b', 'c', 'd'
a b c d
>>>

Note that doing so automatically places a space between the values.

Output to the same line overwriting previous output?

Here's code for Python 3.x:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')

The end= keyword is what does the work here -- by default, print() ends in a newline (\n) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys module for this sort of simple usage. print() actually has a number of keyword arguments which can be used to greatly simplify code.

To use the same code on Python 2.6+, put the following line at the top of the file:

from __future__ import print_function

Print output of loop in same line python?

To avoid printing a new line every time you can use print(key, end="") or also print(key, end=", ") and can then make so that it does not write the last comma.



Related Topics



Leave a reply



Submit