\r的意义
\r
表示将光标的位置回退到本行的开头位置
\b表示将光标的位置回退一位
在python里print会默认进行换行,可以通过修改参数让其不换行
(1) python2中可以在print语句的末尾加上逗号,代码如下:
print "hello",
print "world"
执行结果
hello world 请按任意键继续. . .
(2)在python3里print是一个独立函数,可以通过修改它的默认值来让其不换行
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 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.
flush: whether to forcibly flush the stream.
"""
将end参数改为其他的字符可以让print不换行,来看代码
print("Dream", "it", "possible", sep="-",end="/")
print("Big big world")
运行结果如下:
Dream-it-possible/Big big world Process finished with exit code 0
\r的应用
利用\r可以实现很多有趣的小功能
在命令行实现倒计时功能
# 显示倒计时
import time
for i in range(10):
print("\r离程序退出还剩%s秒" % (9-i), end="")
time.sleep(1)
运行结果如图
命令行实现转圈功能
import time
lst = ["\\", "|", "/", "———"]
for i in range(20):
j = i % 4
print("\r" + lst[j], end="")
time.sleep(0.2)
实现进度条功能
# 进度条功能
import time for i in range(10):
print("\r" + "■"*i, sep="", end="")
time.sleep(0.2)
print("\n下载完成")
运行效果如下
实现删除效果功能
import time
s = "枝上柳绵吹又少,天涯何处无芳草"
l = len(s)
for i in range(l):
print("\r" + s[:l-1-i] + "|", end="")
time.sleep(0.15)
运行效果如图