1. print
函数的基本用法
print
函数是Python中最常用的函数之一,用于在控制台输出信息。其基本语法如下:
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
1.1 输出单个值
print("Hello, World!")
1.2 输出多个值
print("Hello", "World", "!")
2. print
函数的参数
2.1 sep
参数
sep
参数用于指定多个值之间的分隔符,默认是空格。
print("Hello", "World", "!", sep="-")
输出结果:
Hello-World-!
2.2 end
参数
end
参数用于指定输出结束时的字符,默认是换行符\n
。
print("Hello, World!", end=" ")
print("This is a new line.")
输出结果:
Hello, World! This is a new line.
2.3 file
参数
file
参数用于指定输出的目标文件,默认是标准输出sys.stdout
。
with open("output.txt", "w") as file:
print("Hello, World!", file=file)
2.4 flush
参数
flush
参数用于指定是否强制刷新输出缓冲区,默认是False
。
import time
print("Processing...", end="", flush=True)
time.sleep(2)
print(" Done!")
3. 格式化输出
print
函数可以与格式化字符串一起使用,以更灵活地控制输出格式。
3.1 使用%
操作符
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
3.2 使用format
方法
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
3.3 使用f-string(Python 3.6+)
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
4. 高级用法
4.1 输出到文件
with open("output.txt", "w") as file:
print("Hello, World!", file=file)
4.2 输出重定向
import sys
original_stdout = sys.stdout
with open("output.txt", "w") as file:
sys.stdout = file
print("Hello, World!")
sys.stdout = original_stdout
4.3 输出二进制数据
data = b'\x48\x65\x6c\x6c\x6f'
print(data)