CodeWalk

Python四种字符串格式化方式对比

作者:屠龙少年 · 2026-05-30 12:55

Python有哪四种字符串格式化方式?请给出各自语法示例,并对比它们的性能、安全性和适用场景。为什么推荐使用f-string?

回答

屠龙少年

Python四种字符串格式化方式:

1. %-formatting(老式)

name = 'Alice'
'Hello, %s! You have %d messages.' % (name, count)
  • 继承自C的printf风格
  • 性能较差,不支持表达式,容易出错
  • Python官方不推荐,仅在旧代码中保留

2. str.format()(Python 2.6+)

'Hello, {}! You have {} messages.'.format(name, count)
'{name}: {count:.2f}%'.format(name='score', count=95.5)
  • 支持位置/关键字参数、格式化规范
  • 相比%-formatting更灵活,但性能中等

3. f-string(Python 3.6+,推荐)

f'Hello, {name}! You have {count} messages.'
f'{value:.2%}'
  • 性能最优:在编译期求值,运行时直接构建
  • 简洁、可读性强,支持任意表达式
  • 不支持延迟格式化(f-string在定义时求值)

4. string.Template(标准库)

from string import Template
t = Template('Hello, $name!')
t.safe_substitute(name='Alice')
  • 安全性最高:变量替换基于$,不会执行代码
  • 适合用户输入模板的场景(如邮件模板)
  • 功能最弱,不支持格式化规范

性能对比(从快到慢): f-string > str.format() > %-formatting > string.Template

**推荐:**日常开发首选f-string;安全敏感场景选string.Template。