栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

(Python)常用高级函数:print的使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(Python)常用高级函数:print的使用

print函数是Python 3中内置的一种常用函数,主要的功能是打印输出,无返回值。

print函数与文件和流的关系:

在Python 3中,print语句实现打印输出,实际上是把一个或多个对象转换为文本表达式形式,然后发送给标准输出流或者类似的文件流。

print默认的file是sys.stdout,实际上print函数是对sys.stdout的高级封装。

print函数的语法规则如下:

print(*object,sep=' ',end='n',file=sys.stdout,flush=False)

objects -> 可以为一个或多个对象,输出多个对象时,需要用逗号分隔
sep -> 用来间隔多个对象,默认值是一个空格
end -> 用来设定结尾方式,默认值是换行符 n ,也可以换成其他字符串
file -> 要写入的文件对象
flush -> 输出是否被缓存通常由file决定,但是如果flush参数设置为True,则会强制刷新流

以下给出print函数的几种用法实例:

1.使用print函数进行普通输出

# 1.使用print函数进行普通输出
print('Output test !')


# Result
Output test !

2.使用print函数输出多个对象

# 2.使用print函数输出多个对象
Demo_output_0='a'
Demo_output_1='test'
Demo_output_2='2233'

print(Demo_output_0,Demo_output_1,Demo_output_2)


# Result
a test 2233

3.使用print函数输出多个对象,并以@符号作为间隔

# 3.使用print函数输出多个对象,并以@符号作为间隔
Demo_output_0='a'
Demo_output_1='test'
Demo_output_2='2233'

print(Demo_output_0,Demo_output_1,Demo_output_2,sep='@')



# Result
a@test@2233

4.使用print函数进行普通输出,并以#符号作为结尾

# 4.使用print函数进行普通输出,并以#符号作为结尾
print('Output test !',end='###n')


# Result
Output test !###

5.使用print函数将普通输出写入到文件中

# 5.使用print函数将输出写入到文件中
print('Output test !',file=open(r'./Print_result.txt','w'))

Result:

6.print函数中的flush

flush的功能是:强制输出缓冲区中的数据,清空缓冲区。

在print中,flush默认为False。

在print函数中,进入读写流中的数据先被存放到内存中的缓冲区,再写入,如果中途流被close()函数关闭,则缓冲区中的数据会丢失。

# 6.print函数中的flush
import time

for i in range(10):
    print(i)
    time.sleep(0.2)


print('nFlush==False')
for i in range(10):
    print(i,end=' ')
    time.sleep(0.2)
    

print('nFlush==True')
for i in range(10):
    print(i,end=' ',flush=True)
    time.sleep(0.2)



# Result
0
1
2
3
4
5
6
7
8
9

Flush==False
0 1 2 3 4 5 6 7 8 9 
Flush==True
0 1 2 3 4 5 6 7 8 9 

可以看出,Flush==False时,print函数的输出是不匀速的,而设置Flush==True后,print函数保持匀速的输出。

 

Reference:

  1. Python print() 函数 | 菜鸟教程
  2. Python语言Print()方法应用详解_蚂蟥的博客-CSDN博客_pythonprint
  3. python里你有所不知的print语句和flush()方法(内含详细解析及新手易错点)_逆流之路的博客-CSDN博客_print的flush

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号