Most of questions related to this topics here in SO is as follows:
How to print some information on the same line without introducing a new line
Q1 Q2.
Instead, my question is as follows:
I expect to see the following effect,
>> You have finished 10%
where the 10
keep increasing in the same time. I know how to do this in C++ but cannot find a good solution in python.
The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
import sys, time for i in xrange(0, 101, 10): print '\r>> You have finished %d%%' % i, sys.stdout.flush() time.sleep(2) print
The \r
is the carriage return. You need the comma at the end of the print
statement to avoid automatic newline. Finally sys.stdout.flush()
is needed to flush the buffer out to stdout.
For Python 3, you can use:
print("\r>> You have finished {}%".format(i), end='')
You can use keyword arguments to print
:
print('string', end='\r', flush=True)
end='\r'
replaces the default end-of-line behavior with '\r'
flush=True
flushes the buffer, making the printed text appear immediately.In 2.6+ you can use from __future__ import print_function
at the start of the script to enable Python 3 behavior. Or use the old way:
Python's print
puts a newline after each command, unless you suppress it with a trailing comma. So, the print command is:
print 'You have finished {0}%\r'.format(percentage),
Note the comma at the end.
Unfortunately, Python only sends the output to the terminal after a complete line. The above is not a complete line, so you need to flush
it manually:
import sys sys.stdout.flush()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With