Python教程:f-string—更酷的格式化字符串

167 阅读2分钟

在 Python 中,大家都习惯使用 %s 或 format 来格式化字符串,在 Python 3.6 中,有了一个新的选择 f-string

Python教程:f-string—更酷的格式化字符串

使用对比

我们先来看下 Python 中已经存在的这几种格式化字符串的使用比较。

# %s
username = 'tom'
action = 'payment'
message = 'User %s has logged in and did an action %s.' % (username, action)
print(message)
​
# format
username = 'tom'
action = 'payment'
message = 'User {} has logged in and did an action {}.'.format(username, action)
print(message)
​
# f-string
username = 'tom'
action = 'payment'
message = f'User {user} has logged in and did an action {action}.'
print(message)
​
f"{2 * 3}"
# 6
​
comedian = {'name': 'Tom', 'age': 20}
f"The comedian is {comedian['name']}, aged {comedian['age']}."
# 'The comedian is Tom, aged 20.'

相比于常见的字符串格式符 %s 或 format 方法,f-strings 直接在占位符中插入变量显得更加方便,也更好理解。

方便的转换器

f-string 是当前最佳的拼接字符串的形式,拥有更强大的功能,我们再来看一下 f-string 的结构。

f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '

其中 '!s' 调用表达式上的 str(),'!r' 调用表达式上的 repr(),'!a' 调用表达式上的 ascii().

  • 默认情况下,f-string 将使用 str(),但如果包含转换标志 !r,则可以使用 repr()
class Person:
 def __init__(self, name, age):
 self.name = name
 self.age = age
​
 def __str__(self):
 return f'str - name: {self.name}, age: {self.age}'
​
 def __repr__(self):
 return f'repr - name: {self.name}, age: {self.age}'
​
p = Person('tom', 20)
f'{p}'
# str - name: tom, age: 20
​
f'{p!r}'
# repr - name: tom, age: 20
  • 转换标志 !a
a = 'a string'
f'{a!a}'
# "'a string'"
  • 等价于
f'{repr(a)}'
# "'a string'"

性能

f-string 除了提供强大的格式化功能之外,还是这三种格式化方式中性能最高的实现。

>>> import timeit
>>> timeit.timeit("""name = "Eric"
... age = 74
... '%s is %s.' % (name, age)""", number = 10000)
0.003324444866599663
>>> timeit.timeit("""name = "Eric"
... age = 74
... '{} is {}.'.format(name, age)""", number = 10000)
0.004242089427570761
>>> timeit.timeit("""name = "Eric"
... age = 74
... f'{name} is {age}.'""", number = 10000)
0.0024820892040722242

使用 Python 3.6+ 的同学,使用 f-string 来代替你的 format 函数,以获得更强大的功能和更高的性能。

更多的Python学习教程也会继续为大家更新!