【Python】Python中字符串格式化的方式有哪几种?

Python中字符串格式化的常见方式有:

  1. % formatting:
## python www.itzhimei.com 代码
name = 'John'
"Hello %s" % name # 'Hello John'

"Age: %d" % 25
  1. str.format():
## python www.itzhimei.com 代码
"Hello {}, you are {} years old".format(name, 25)

"Hello {name}, you are {age} years old".format(name=name, age=25)
  1. f-strings (Python 3.6+):
## python www.itzhimei.com 代码
name = 'John'
age = 25
f"Hello {name}, you are {age} years old"
  1. Template strings:
## python www.itzhimei.com 代码
from string import Template
t = Template("Hello $name, you are $age years old")
t.substitute(name=name, age=25)
  1. formatted string literals (Python 3.8+):
## python www.itzhimei.com 代码
name = 'John'
f'Hello {name}, you are {25} years old'

其中% formatting和str.format()使用最广泛。f-strings和formatted string literals是新式格式化方法,简洁快速。

选择合适的字符串格式化方法可以使代码更简洁优雅。