print()函数完型

在Python中,print()函数用于将信息输出到控制台,其基本语法和常见用法如下:

基本语法

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

参数说明

  1. value1, value2, ...:要输出的值(可以是多个,用逗号分隔)
  2. sep:多个值之间的分隔符,默认是空格' '
  3. end:输出结束时的字符,默认是换行符'\n'
  4. file:输出的目标位置,默认是控制台(sys.stdout),也可以是文件对象
  5. flush:是否立即刷新缓冲区,默认是False

常用示例

  1. 输出单个值
print("Hello, World!")  # 输出字符串
print(42)               # 输出数字
print(True)             # 输出布尔值
  1. 输出多个值
name = "Alice"
age = 30
print("Name:", name, "Age:", age)  # 多个值用逗号分隔
  1. 自定义分隔符和结束符
print("apple", "banana", "cherry", sep=", ")  # 用逗号加空格分隔
print("Hello", end="! ")                      # 结束符改为感叹号加空格
print("World")
  1. 输出到文件
with open("output.txt", "w") as f:
    print("This will be written to the file", file=f)
  1. 格式化输出
    可以结合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()函数的基本用法,能够满足大多数输出需求。

posted @ 2025-09-01 15:29  nxhujiee  阅读(23)  评论(0)    收藏  举报