print()是Python中最常用的内置函数之一,用于将内容输出到标准输出(通常是控制台)。从Python 3开始,print是一个函数,而在Python 2中它是一个语句。
基本语法
python
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
参数说明
-
objects:要打印的一个或多个对象,用逗号分隔
-
sep:分隔符,默认为一个空格
-
end:结束字符,默认为换行符
\n -
file:输出流,默认为
sys.stdout(控制台) -
flush:是否立即刷新输出流,默认为
False
基本用法
1. 打印单个值
python
print("Hello, World!") # 输出: Hello, World!
2. 打印多个值
python
print("Hello", "World", "!") # 输出: Hello World !
3. 使用不同的分隔符
python
print("2023", "12", "31", sep="-") # 输出: 2023-12-31
print("one", "two", "three", sep=", ") # 输出: one, two, three
4. 修改结束字符
python
print("Hello", end=" ") # 不换行,以空格结束
print("World") # 输出: Hello World
5. 打印到文件
python
with open("output.txt", "w") as f:
print("This will be written to a file", file=f)
格式化输出
1. 使用%格式化(旧式)
python
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age)) # 输出: Name: Alice, Age: 25
2. 使用str.format()方法
python
print("Name: {}, Age: {}".format(name, age)) # 输出: Name: Alice, Age: 25
print("Name: {1}, Age: {0}".format(age, name)) # 位置参数
print("Name: {n}, Age: {a}".format(n=name, a=age)) # 关键字参数
3. 使用f-string(Python 3.6+推荐)
python
print(f"Name: {name}, Age: {age}") # 输出: Name: Alice, Age: 25
print(f"Next year, {name} will be {age + 1} years old")
高级用法
1. 打印特殊字符
python
print("Line1\nLine2") # 换行
print("Tab\tseparated") # 制表符
print("This is a backslash: \\") # 反斜杠
print("He said, \"Hello\"") # 引号
2. 打印原始字符串(忽略转义)
python
print(r"C:\new_folder\file.txt") # 输出: C:\new_folder\file.txt
3. 打印多行字符串
python
print("""这是一个
多行
字符串""")
4. 控制输出对齐
python
# 左对齐,总宽度10
print(f"{'left':<10} aligned") # 输出: left aligned
# 右对齐,总宽度10
print(f"{'right':>10} aligned") # 输出: right aligned
# 居中对齐,总宽度10
print(f"{'center':^10} aligned") # 输出: center aligned
5. 数字格式化
python
pi = 3.1415926535
print(f"Pi is approximately {pi:.2f}") # 输出: Pi is approximately 3.14
number = 1000000
print(f"Formatted number: {number:,}") # 输出: Formatted number: 1,000,000
6. 打印彩色文本(终端)
python
# ANSI转义序列
print("\033[31mThis is red text\033[0m") # 红色文本
print("\033[1;32mThis is bold green text\033[0m") # 粗体绿色文本
注意事项
-
在Python 2中,
print是一个语句而不是函数,语法为print "Hello" -
大量使用
print可能会影响程序性能,特别是在循环中 -
在生产环境中,考虑使用日志模块(logging)代替
print进行调试和记录 -
print默认会添加换行符,如果不想要换行,可以设置end=""
实际应用示例
python
# 打印表格数据
headers = ["Name", "Age", "Country"]
data = [
["Alice", 25, "USA"],
["Bob", 30, "UK"],
["Charlie", 35, "Canada"]
]
# 计算列宽
col_width = max(len(word) for row in [headers] + data for word in row) + 2
# 打印表头
print("".join(word.ljust(col_width) for word in headers))
print("-" * (col_width * len(headers)))
# 打印数据行
for row in data:
print("".join(str(word).ljust(col_width) for word in row))
输出:
text
Name Age Country ------------------------- Alice 25 USA Bob 30 UK Charlie 35 Canada
print()函数虽然简单,但通过合理使用其参数和格式化方法,可以实现非常丰富的输出效果。
Python print()函数用法全解析
2716

被折叠的 条评论
为什么被折叠?



