Python字符串格式化方法

Python 旧式字符串格式化

旧式字符串格式化方法是指使用 % 操作符来进行字符串格式化。这种方法类似于 C 语言中的 printf 样式格式化,是 Python 早期版本中常用的字符串格式化技术。虽然在现代 Python 中推荐使用 str.format() 或 f-strings,但对于理解历史代码或兼容旧版本的 Python,了解 % 操作符仍然很有必要。

% 操作符的基本用法

% 操作符允许你在字符串中插入占位符,然后通过 % 操作符后面跟一个元组来替换这些占位符。

基本示例
name = "Alice"
age = 30

# 使用 %s 和 %d 占位符
message = "My name is %s and I am %d years old." % (name, age)
print(message)

占位符类型

% 操作符支持多种类型的占位符,常见的包括:

  • %s: 字符串
  • %d: 整数
  • %f: 浮点数
  • %c: 字符
  • %%: 百分号本身
示例
# 字符串
print("Hello, %s!" % "world")

# 整数
print("The number is %d" % 42)

# 浮点数
print("The value is %f" % 3.14159)

# 字符
print("The first letter is %c" % 'A')

# 百分号
print("This is 100%% complete")

格式化选项

你可以通过在占位符后添加格式化指令来控制输出的格式。例如:

  • .2f: 控制浮点数的小数位数。
  • -: 左对齐。
  • 0: 使用零填充。
  • ^: 居中。
示例
value = 3.14159
print("The value is %.2f" % value)  # 控制小数位数
print("The value is %-10.2f" % value)  # 左对齐
print("The value is %010.2f" % value)  # 使用零填充
print("The value is ^10.2f" % value)  # 居中

复杂示例

下面是一个更复杂的示例,展示了如何使用 % 操作符进行字符串格式化:

name = "Bob"
age = 25
height = 180.5

# 使用多个占位符
message = "My name is %s, I am %d years old, and my height is %.2f cm." % (name, age, height)
print(message)

# 使用百分比
percentage = 0.75
message = "The completion percentage is %d%%" % (percentage * 100)
print(message)

# 使用左对齐
value = 12345
message = "The value is %-10d" % value
print(message)

输出

My name is Bob, I am 25 years old, and my height is 180.50 cm.
The completion percentage is 75%
The value is 12345

Python 新式字符串格式化

Python 中有几种不同的字符串格式化方法,其中新式的字符串格式化主要是指使用 f-string(格式化字符串文字)和 str.format() 方法。这两种方法相比旧式的 % 格式化更加现代、灵活和易于阅读。

1. f-string (格式化字符串文字)

f-string 是 Python 3.6 版本引入的新特性,它提供了一种简洁且直观的方式来格式化字符串。f-string 以字母 fF 开头,字符串内部可以直接嵌入变量和表达式。

1.1 f-string 基础用法
name = "Alice"
age = 30

# 使用 f-string 格式化字符串
message = f"Hello, my name is {name} and I am {age} years old."
print(message)  # 输出: Hello, my name is Alice and I am 30 years old.
1.2 f-string 中的表达式

在 f-string 中不仅可以插入变量,还可以直接使用表达式。

x = 10
y = 20

result = f"The sum of {x} and {y} is {x + y}."
print(result)  # 输出: The sum of 10 and 20 is 30.
1.3 控制格式输出

f-string 还支持使用格式规范符来控制输出格式。

pi = 3.141592653589793

# 格式化浮点数
formatted_pi = f"Pi is approximately {pi:.2f}"
print(formatted_pi)  # 输出: Pi is approximately 3.14
1.4 使用函数和方法

f-string 中可以使用函数和方法。

def greet(name):
    return f"Hello, {name}!"

# 使用函数
greeting = f"{greet('Bob')}"
print(greeting)  # 输出: Hello, Bob!
2. str.format() 方法

str.format() 方法是另一种常见的字符串格式化方法,在 Python 2.6 版本引入,现在仍然广泛使用。

2.1 基础用法
name = "Alice"
age = 30

# 使用 str.format() 格式化字符串
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)  # 输出: Hello, my name is Alice and I am 30 years old.
2.2 使用索引

如果参数列表中有多个元素,可以使用索引指定位置。

x = 10
y = 20

result = "The sum of {0} and {1} is {2}".format(x, y, x + y)
print(result)  # 输出: The sum of 10 and 20 is 30
2.3 使用关键字参数

也可以使用关键字参数来指定变量。

pi = 3.141592653589793

# 使用关键字参数
formatted_pi = "Pi is approximately {:.2f}".format(pi)
print(formatted_pi)  # 输出: Pi is approximately 3.14
2.4 使用类的方法

可以调用类的方法来格式化字符串。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greeting(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person = Person("Alice", 30)

# 使用类的方法
greeting = person.greeting()
print(greeting)  # 输出: Hello, my name is Alice and I am 30 years old.

总结

f-string 和 str.format() 方法都是现代 Python 中推荐使用的字符串格式化方法。f-string 更加简洁明了,尤其是在需要嵌入表达式和方法调用的情况下更为方便。str.format() 方法则提供了更多的灵活性,尤其是在需要指定位置或使用关键字参数的情况下。

根据具体情况和个人喜好选择合适的方法即可。对于新项目或者 Python 3.6+ 的版本,推荐使用 f-string。而对于需要兼容较旧版本 Python 的情况,可以选择使用 str.format()和旧式使用%的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

知识的宝藏

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

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

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

打赏作者

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

抵扣说明:

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

余额充值