Print () should be the first Python function a beginner encounters, because almost all introductory lessons start with print(‘ Hello world ‘). In fact, print() is one of the most frequently used functions by programmers, and a favorite debugging tool for many programmers. But do you really know anything about the print() function?
1. Typewriter effects
If you don’t know the flush parameter of print(), it’s hard to achieve the typewriter effect shown below: Print () is like a naughty kid. If you ask him to print for you, he will do it, but not immediately. Set Flush =True to cause the child to execute the command immediately.
# -*- coding: utf-8 -*-
import time
def printer(text, delay=0.2) :
""" Typewriter effect """
for ch in text:
print(ch, end=' ', flush=True)
time.sleep(delay)
printer('Iron esaber is the first magic sword in Jin Yong's novels, and it is unbeatable in the world. ')
Copy the code
2. Rotating progress indicator In Linux system text interface, the most commonly used progress indicator is a rotating pattern composed of horizontal and vertical slashes.
Python can easily do this, too, thanks to the ‘\b’ character. ‘\b’ acts as a backspace key on the keyboard, allowing us to erase and reprint the last character we just printed. This effect also requires that the argument Flush be set to true.
# -*- coding: utf-8 -*-
"Have a problem and no one to answer it? We have created a Python learning exchange group: 778463939 to find people who have the same interests as you. The group also has great video tutorials and PDF e-books. ' ' '
import time
def waiting(cycle=20, delay=0.1) :
""" Rotary progress indicator ""
for i in range(cycle):
for ch in [The '-'.'\ \'.'|'.'/'] :print('\b%s'%ch, end=' ', flush=True)
time.sleep(delay)
waiting()
Copy the code
Reversing the character order changes the rotation direction. We can also change the first character ‘- ‘to ‘–‘ :
3. Overlay printing effect
‘\b’ backs up a character, and ‘\r’ backs up a line. With the help of ‘\ R’, the print effect of full line overlay can be achieved:
Note that if the entire line is overwritten, the length of the new string cannot be smaller than the length of the original string. Otherwise, the previous printed content is left. This effect also requires that the argument Flush be set to true.
# -*- coding: utf-8 -*-
import time
def cover(cycle=100, delay=0.2) :
""" Overlay printing effect ""
for i in range(cycle):
s = '\r%d'%i
print(s.ljust(3), end=' ', flush=True)
time.sleep(delay)
cover()
Copy the code