Python print()函数

print()函数是 Python 内置函数之一,用于输出指定的对象。它可以接受多个参数,用逗号分隔,它们将被依次输出,并且默认情况下它们之间会用空格分隔。在输出完成之后,print()函数会自动在末尾添加一个换行符。

print()函数语法

它的一般语法如下:

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

其中:

  • objects表示要输出的对象,可以有多个,用逗号分隔。
  • sep表示分隔符,默认是一个空格。
  • end表示结束符,默认是一个换行符。
  • file表示输出到哪个文件,默认是标准输出。
  • flush表示是否强制刷新缓存区,默认是不刷新。

print()函数示例

下面是一些常见的示例:

print("Hello, world!")   # 输出一个字符串
print(123)               # 输出一个整数
print(3.14)              # 输出一个浮点数
print("Hello", "world")  # 输出多个参数
print(['a','b','c'])     # 输出一个列表

程序输出:

Hello, world!
123
3.14
Hello world
['a', 'b', 'c']

使用sep参数可以修改分隔符:

print("apple", "banana", "orange", sep=",")   # 使用逗号分隔

程序输出:

apple,banana,orange

使用end参数可以修改结束符:

print("Hello", end=" ")
print("world")

程序输出:

Hello world

使用file参数可以将输出写入到文件:

with open("output.txt", "w") as f:
    print("Hello, world!", file=f)

将字符串 "Hello, world!" 写入到文件 output.txt 中。

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/python-built-in-functions/python-print.html

分类: 计算机技术
推荐阅读:
Golang实现获取文件的后缀名(扩展名) Golang通过调用 path.Ext() 函数,可获取文件的后缀名。
使用PyInstaller打包PyQt5程序发生ImportError错误的解决办法 ImportError: unable to find Qt5Core.dll on PATH ,Failed to execute script main
使用pip安装PySide6 在安装PySide6之前,你必须先安装Python 3.6 以上版本;你可以使用pip命令进行安装,该命令将安装PySide6最新版本;
gin+Nginx获取真实的客户端IP 当使用Nginx为Golang gin程序做反向代理(端口转发)或负载均衡时,gin得到的客户端IP为127.0.0.1,这是由于Nginx没有正确配置导致;
应该掌握的Linux终端常用快捷键 本篇内容将介绍在Linux系统(例如Debian、CentOS、ubuntu等)终端下使用快捷键来加快你的输入速度,节省你的时间;
warning: implicit declaration of function 'getpid' 解决方法 在C程序中使用getpid()获取进程识别码时,可能会出现 warning: implicit declaration of function 'getpid'; did you mean 'getenv'? [-Wimplicit-function-declaration] 这样的警告信息;