在 Python 编程的世界里,字符串格式化是一项至关重要的技能,无论是在日常的文本输出、日志记录,还是复杂的数据处理和用户界面展示中,合理运用字符串格式化方法都能让我们的代码更加清晰、高效和专业。
1. %
操作符(旧式格式化)
%
操作符用于旧式的字符串格式化。它需要一个格式字符串,其中包含一些占位符(如 %s
、%d
等),和一个元组,元组中的元素将被插入到格式字符串的相应位置。
%s
:字符串占位符%d
:整数占位符%f
:浮点数占位符%(name)s
:命名占位符,可以在格式化字符串中指定变量的名字
name = "Alice" | |
age = 30 | |
print("My name is %s and I am %d years old." % (name, age)) # 使用位置参数 | |
data = {'name': 'Bob', 'age': 25} | |
print("Hello, %(name)s. You are %(age)d years old." % data) # 使用命名参数 |
2. str.format()
方法
str.format()
方法提供了更强大和灵活的字符串格式化功能。它可以使用位置参数、关键字参数,并且支持更复杂的格式化选项。
{}
:占位符,可以使用位置索引或关键字:
后可以跟格式化选项,如宽度、精度、对齐方式等
示例:
print("Hello, {} and {}".format("Alice", 30)) # 使用位置参数 | |
print("Hello, {name}. You are {age} years old.".format(name="Bob", age=25)) # 使用关键字参数 | |
print("The value of pi is approximately {:.3f}".format(3.1415926)) # 保留3位小数 |
3. f-string(Python 3.6+)
f-string 是 Python 3.6 引入的一种新的字符串格式化方法,它允许在字符串中嵌入表达式,这些表达式在运行时会被求值并转换为字符串。
- 在字符串前加上
f
或F
前缀 - 在字符串内部使用大括号
{}
包围表达式
name = "Charlie" | |
age = 40 | |
print(f"Hello, {name}. You are {age} years old.") | |
price = 123.45678 | |
print(f"The price is {price:.2f}") # 保留2位小数 |
4. string.Template
string.Template
类提供了一种基于模板的字符串替换方法。它使用 $
符号作为占位符的前缀,并在 substitute()
方法中提供替换值。
- 定义模板字符串,使用
$
和变量名作为占位符 - 使用
substitute()
方法进行替换
from string import Template | |
template = Template("Hello, $name. You are $age years old.") | |
data = {'name': 'Dave', 'age': 50} | |
result = template.substitute(data) | |
print(result) |
5. locale
模块
locale
模块提供了访问特定地域文化习惯的功能,包括日期、时间、货币等的格式化。它允许你根据用户的本地化设置来格式化字符串。
- 使用
setlocale()
方法设置本地化环境 - 使用
locale
模块提供的函数(如currency()
)进行格式化
import locale | |
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # 设置本地化环境为美国英语 | |
price = 1234.56 | |
formatted_price = locale.currency(price, grouping=True) | |
print(formatted_price) # 输出可能类似于 "$1,234.56" |
这些格式化方法各有特点,你可以根据具体需求选择最适合的方法。在现代 Python 代码中,f-string 由于其简洁性和可读性而变得越来越流行。