python中的print函数

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值