python中\r的意义及用法

原文出处:https://www.cnblogs.com/zzliu/p/10156658.html

\r 表示将光标的位置回退到本行的开头位置

\b表示将光标的位置回退一位

在python里print会默认进行换行,可以通过修改参数让其不换行
(1) 在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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值