python中print格式化输出

在 Python 中,格式化输出可以使用多种方式来控制文本和变量的显示方式。常见的格式化方法包括 % 格式化、str.format() 方法和 f-strings(格式化字符串字面量)。下面分别介绍这些常用的格式化方法:

1. 使用 % 进行格式化输出

这种方式是较早的格式化方法,类似于 C 语言中的格式化输出。

基本语法
print("格式化字符串 % 格式化项" % (变量))
示例
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))

输出:

My name is Alice and I am 25 years old.
常用格式化符号
格式化符号描述
%s字符串
%d整数
%f浮点数
%x十六进制数
%%百分号
浮动小数位数
pi = 3.14159265
print("Pi to 2 decimal places: %.2f" % pi)

输出:

Pi to 2 decimal places: 3.14

2. 使用 str.format() 进行格式化输出

这种方式相较于 % 更为灵活,支持位置参数和关键字参数。

基本语法
print("格式化字符串 {}".format(变量))
示例
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

输出:

My name is Alice and I am 25 years old.
位置参数和关键字参数
# 位置参数
print("My name is {} and I am {} years old.".format(name, age))

# 关键字参数
print("My name is {name} and I am {age} years old.".format(name="Alice", age=25))

输出:

My name is Alice and I am 25 years old.
格式化数字
pi = 3.14159265
print("Pi to 2 decimal places: {:.2f}".format(pi))

输出:

Pi to 2 decimal places: 3.14
指定字段宽度和对齐
name = "Alice"
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))

输出:

Left       |   Center   |      Right

3. 使用 f-strings(格式化字符串字面量)

这是 Python 3.6 引入的一种更简洁和高效的字符串格式化方式。它允许你直接在字符串中嵌入变量。

基本语法
print(f"格式化字符串 {变量}")
示例
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

输出:

My name is Alice and I am 25 years old.
格式化数字
pi = 3.14159265
print(f"Pi to 2 decimal places: {pi:.2f}")

输出:

Pi to 2 decimal places: 3.14
指定字段宽度和对齐
print(f"{'Left':<10} | {'Center':^10} | {'Right':>10}")

输出:

Left       |   Center   |      Right
表达式和计算

f-strings 还可以嵌入表达式和计算:

x = 10
y = 5
print(f"The sum of {x} and {y} is {x + y}.")

输出:

The sum of 10 and 5 is 15.

4. 使用 format() 方法进行高级格式化

str.format() 方法也支持更复杂的格式化,例如填充、对齐、精度控制等。

示例
# 填充和对齐
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))

# 数字格式化
pi = 3.14159265
print("Pi: {:.2f}".format(pi))

# 百分比格式
value = 0.1234
print("Percentage: {:.2%}".format(value))

输出:

Left       |   Center   |      Right
Pi: 3.14
Percentage: 12.34%

总结

  • % 格式化:传统的方式,适用于简单的格式化。
  • str.format():更加灵活,可以使用位置参数、关键字参数和复杂格式。
  • f-strings:推荐的方式,简洁、易读,并且具有最好的性能。适用于大部分情况。

在 Python 3.6 及之后的版本中,推荐使用 f-strings,因为它既简洁又高效。如果需要兼容旧版本的 Python(如 2.x),则可以使用 str.format()% 格式化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值