python中\r的意义及用法

\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可以实现很多有趣的小功能

在命令行实现倒计时功能

1 # 显示倒计时
2 import time
3 for i in range(10):
4     print("\r离程序退出还剩%s秒" % (9-i), end="")
5     time.sleep(1)

 

运行结果如图

 

命令行实现转圈功能

1 import time
2 lst = ["\\", "|", "/", "———"]
3 for i in range(20):
4     j = i % 4
5     print("\r" + lst[j], end="")
6     time.sleep(0.2)

实现进度条功能

1 # 进度条功能
2 import time
3 
4 for i in range(10):
5     print("\r" + ""*i, sep="", end="")
6     time.sleep(0.2)
7 print("\n下载完成")

 运行效果如下

 

 

实现删除效果功能

1 import time
2 s = "枝上柳绵吹又少,天涯何处无芳草"
3 l = len(s)
4 for i in range(l):
5     print("\r" + s[:l-1-i] + "|", end="")
6     time.sleep(0.15)

运行效果如图

 

转载于:https://www.cnblogs.com/zzliu/p/10156658.html

  • 14
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值