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
Without knowing the flush argument for print(), it is difficult to achieve the typewriter effect shown below:
Print () is like a naughty kid. If you ask him to print for you, he will definitely do it, but he may not do it immediately. Set Flush =True to cause the child to execute the command immediately.
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. Rotary progress indicator
In Linux 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.
"Have a problem and no one to answer it? We have created a Python learning QQ group: 531509025. We are looking for friends with similar interests to help each other. We also have 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.
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