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

本文深入讲解了Python中的print函数,包括其基本语法、参数说明以及如何通过调整参数实现不同的输出效果,例如改变输出间隔和结束符等。此外,还探讨了print函数与文件流之间的交互作用,以及flush参数的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Think@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值