print()函数完型
在Python中,print()函数用于将信息输出到控制台,其基本语法和常见用法如下:
基本语法
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
参数说明
- value1, value2, ...:要输出的值(可以是多个,用逗号分隔)
- sep:多个值之间的分隔符,默认是空格
' ' - end:输出结束时的字符,默认是换行符
'\n' - file:输出的目标位置,默认是控制台(
sys.stdout),也可以是文件对象 - flush:是否立即刷新缓冲区,默认是
False
常用示例
- 输出单个值
print("Hello, World!") # 输出字符串
print(42) # 输出数字
print(True) # 输出布尔值
- 输出多个值
name = "Alice"
age = 30
print("Name:", name, "Age:", age) # 多个值用逗号分隔
- 自定义分隔符和结束符
print("apple", "banana", "cherry", sep=", ") # 用逗号加空格分隔
print("Hello", end="! ") # 结束符改为感叹号加空格
print("World")
- 输出到文件
with open("output.txt", "w") as f:
print("This will be written to the file", file=f)
- 格式化输出
可以结合f-string、format()方法或%运算符进行格式化:
name = "Bob"
score = 95
print(f"{name} scored {score} points") # f-string(Python 3.6+)
print("{} scored {} points".format(name, score))
print("%s scored %d points" % (name, score))
这些是print()函数的基本用法,能够满足大多数输出需求。

浙公网安备 33010602011771号