使用不同参数的print()函数的5个用例
发布时间:2023-06-14 09:59:53
1. 使用sep参数将两个字符串进行拼接输出:
print("Hello", "World", sep="-")
输出结果:Hello-World
2. 使用end参数在同一行输出两个字符串:
print("Hello", end=" ")
print("World")
输出结果:Hello World
3. 使用file参数将输出结果写入txt文件:
f = open("output.txt", "w")
print("Hello, World!", file=f)
f.close()
在output.txt文件中保存的内容为:Hello, World!
4. 使用format参数输出格式化字符串:
name = "Tom"
age = 20
print("My name is {0} and I am {1} years old".format(name, age))
输出结果:My name is Tom and I am 20 years old
5. 使用flush参数立即刷新输出缓冲区:
import time
for i in range(10):
print(i, end=" ", flush=True)
time.sleep(1)
每个数字之间相隔1秒输出,通过flush参数可以立即输出当前数字。
