Python 内建函数 - print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

本文介绍了Python的内建函数print(),包括如何指定分隔符sep、结束符end,以及如何指定输出流file。print()函数将对象转换为字符串并输出,支持关键字参数flush用于强制刷新流。在Python 3.3版本中添加了flush参数。

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

Manual

Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(…) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

直译

objects打印到文本流file,以sep分隔,然后以end结尾。如果sependfile存在,必须作为关键字参数给定。
所有非关键字参数都转换为字符串(好比用str()处理),并写入到流,以sep分隔,然后以end结尾。sepend都必须是字符串,它们也可以是None,这表示使用默认值。如果没有给定objects,print()将只写入end
file参数必须是具有write(string)方法的对象,如果它不出现或为None,将使用sys.stdout。虽然打印的参数转化为文本字符串,但print()不能使用二进制模式文件对象。对于这种情况,可以使用file.write(…)替代。
输出是否缓冲,通常由file决定,但如果flush关键字参数为True,则会强制刷新流。

version 3.3变更: 增加flush关键字参数。

实例

>>> with open('example.txt', 'w') as f:
    print('Hello world!', file=f)

>>> with open('example.txt', 'r') as f:
    print(f.readline())

Hello world!

>>> with open('example.txt', 'r') as f:
    print(f.readlines())

['Hello world!\n']
# 默认以\n结尾

拓展阅读

sys.stdout

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值