Python字符串格式化详解:从基础到高级技巧377


Python 提供了多种强大的方法将各种数据类型转换成字符串格式,这在处理文本、日志记录、数据可视化和与其他系统交互时至关重要。本文将深入探讨 Python 中的字符串格式化技术,从基础的 f-string 开始,逐步讲解更高级的 `()` 方法和旧式的 `%` 操作符,并比较它们的优缺点,最终帮助你选择最适合你项目需求的方案。

1. f-strings (Formatted String Literals): 最简洁高效的选择

f-strings 是 Python 3.6 引入的,它以简洁性和可读性而闻名。通过在字符串前添加 `f` 或 `F`,并在花括号 `{}` 内嵌入表达式,可以直接将变量值插入到字符串中。这使得代码更加清晰易懂。

```python
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.") # 输出: My name is Alice and I am 30 years old.
```

f-strings 还支持表达式求值、函数调用以及格式说明符,极大地扩展了它的功能。

```python
import math
radius = 5
print(f"The area of the circle is { * radius2:.2f}") # 输出: The area of the circle is 78.54
```

在这个例子中,`.2f` 指定了浮点数保留两位小数。

2. `()` 方法:灵活且功能强大的选择

`()` 方法提供了一种更灵活的字符串格式化方式。它使用花括号 `{}` 作为占位符,并通过 `format()` 方法的参数来填充这些占位符。可以使用位置参数或关键字参数。

```python
name = "Bob"
age = 25
print("My name is {} and I am {} years old.".format(name, age)) # 输出: My name is Bob and I am 25 years old.
print("My name is {0} and I am {1} years old.".format(name, age)) # 输出: My name is Bob and I am 25 years old. (位置参数)
print("My name is {name} and I am {age} years old.".format(name="Charlie", age=35)) # 输出: My name is Charlie and I am 35 years old. (关键字参数)
```

`()` 也支持格式说明符,可以对输出进行更精细的控制,例如对齐、填充、宽度等。

```python
print("{:>10}".format("hello")) # 右对齐,宽度为10
print("{:

2025-06-01


上一篇:Python WHL文件命名规范与最佳实践

下一篇:Pythonic 歌曲伪代码生成与分析:从旋律到代码