博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中\r的意义及用法
阅读量:7042 次
发布时间:2019-06-28

本文共 1537 字,大约阅读时间需要 5 分钟。

\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 worldProcess finished with exit code 0

 

\r的应用

利用\r可以实现很多有趣的小功能

在命令行实现倒计时功能

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

 

运行结果如图

 

命令行实现转圈功能

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

实现进度条功能

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

 运行效果如下

 

 

实现删除效果功能

1 import time2 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

你可能感兴趣的文章
二、数据挖掘---认识数据
查看>>
windows下apache+php+mysql 环境配置方法
查看>>
solais 10中执行crontab -e报unkown terminal type
查看>>
jar包下载网址
查看>>
virtualbox使用总结
查看>>
CentOS7上搭建VNC服务
查看>>
Apache select与Nginx epoll模型区别
查看>>
Vue组件入门
查看>>
广告条
查看>>
『中级篇』Docker-cloud介绍(54)
查看>>
到期的Navicat需要注册码--解决方案
查看>>
【Unity3D基础教程】给初学者看的Unity教程(二):所有脚本组件的基类 -- MonoBehaviour的前世今生...
查看>>
×××小程序接口调试
查看>>
OpenSSL安装
查看>>
我是如何沉迷于linux系统的?
查看>>
微软正式释出基于 Chromium 的全新版本 Edge
查看>>
SHELL菜单select练习
查看>>
aaa
查看>>
wwballizer以及awstat下的apache日志监控
查看>>
NO3.Shell脚本学习——编写Shell脚本
查看>>