python 字符串格式化方法

在 Python 中,字符串模板主要用于动态生成文本。 它们特别适用于需要根据变量值构建字符串的场景,如生成报告、配置文件、用户消息等。Python 提供了几种不同的方式来实现字符串模板功能,包括 f-strings 和 string.Template 类。

1. F-Strings(格式化字符串字面量)

使用场景:F-strings 是从 Python 3.6 开始引入的,因其简洁性和直观性而成为首选方法。 它非常适合于任何需要将变量或表达式嵌入到字符串中的场景。

例子

name = "Alice"
age = 30
formatted_string = f"Hello, {name}! You are {age} years old."
print(formatted_string)  # 输出: Hello, Alice! You are 30 years old.

你还可以在 f-strings 中直接执行表达式:

a = 5
b = 10
result = f"The sum of {a} and {b} is {a + b}."
print(result)  # 输出: The sum of 5 and 10 is 15.

2. string.Template

使用场景:当处理来自外部的数据(例如用户输入或配置文件)时,string.Template 提供了一种更安全的方法进行字符串替换。相比于其他方法,它的语法更加简单,并且可以避免一些潜在的安全问题。

例子

from string import Template

t = Template('Hey $name!')
print(t.substitute(name='Alice'))  # 输出: Hey Alice!

使用safe_substitute避免异常

template = Template('Hey $name, you are $age years old.')
print(template.safe_substitute(name='Alice'))  # 输出: Hey Alice, you are $age years old.

string.Template 还支持默认值和多行模板:

s = Template('''Dear $title $name,
Thank you for your email. We will contact you as soon as possible.
Best regards,
$sender''')

print(s.substitute(title='Ms.', name='Smith', sender='Support Team'))

总结

  • f-strings 提供了强大的功能和简洁的语法,适合大多数需要动态生成字符串的场景。
  • string.Template 更加安全,适合处理不可信的输入数据(如用户输入), 并提供了一个简单的语法用于基本的字符串替换任务。

选择哪种方法取决于你的具体需求,包括安全性考虑、代码可读性以及对表达式求值的支持等。对于大多数应用,尤其是当你使用的是 Python 3.6 或更高版本时,推荐优先考虑使用 f-strings。