使用 f-string 格式化字符串的七个层级

f-string是Python 3.6推出的一种简单而不同的字符串格式技术,可以优雅地表达Python字符串。除非您仍在使用旧的 Python 版本,否则在格式化字符串时,f 字符串绝对应该是您的首选。因为它可以通过一个迷你语法满足您的所有要求,甚至运行字符串的表达式。本文将深入探讨这项技术从初级到深度的7个层次。在了解它们之后,您可能会成为字符串格式化大师。

1. 轻松从变量显示值

使用 f 字符串只需要做两件事:

在字符串前添加一个小写的f;

使用f字符串中以{variable_name}插值变量.

name = 'Yang'
title = 'full stack hacker'
print(f'{name} is a {title}.')
# Yang is a full stack hacker.

如上所示,在 f 字符串机制的帮助下,我们可以编写简单且更少的代码,以便在字符串中显示更多代码。它完美地呼应了 Python 的禅宗。

"简单总比复杂好。

2. 数字格式化

有时仅仅显示原始值可能无法满足我们的需求,但是直接修改原始变量通常不是个好主意,因为变量可能在其他地方使用。不用担心,Python f字符串还支持"格式规范迷你语言",它使我们能够根据自己喜欢的方式在 f 字符串中格式化值,尤其是数字。

pi = 3.1415926
print(f'Pi is approximately equal to {pi:.2f}')
# Pi is approximately equal to 3.14

id = 1  # need to print a 3-digit number
print(f"The id is {id:03d}")
# The id is 001

# need to add separator

N = 1000000000  
print(f'His networth is {N:,d}')
# His networth is $1,000,000,000

以上示例仅显示了冰山一角。对于格式规格语法的完整列表,相应的官方文档是您最好的朋友。

3. 正确打印特殊字符

我们可以通过 f 字符串打印这些字符或其他特殊字符吗?比如''和{}。是的,当然。但语法有点棘手。让我们来看看。

3.1 打印引号

正如我们所知,反斜线\是常用的转义字符,用于调用对其以下字符的替代解释。对于 f 字符串,我们需要注意一条规则:\在 f 字符串表达式的括号{}中不起作用。

name = 'Yang'
# Correct Way:
print(f'\'{name}\' is a full stack hacker.')
# 'Yang' is a full stack hacker.

# 错误方式:
print(f'{\'name\'} is a full stack hacker.')
# SyntaxError: f-string expression part cannot include a backslash

3.2 打印双括号{}

用 f字符串打印{}的方法是不同的, 非常容易出bug。这次我们不能使用反斜线。

name = 'Yang'

# 1
print(f'{name} is a full stack hacker.')
# 'Yang' is a full stack hacker.

# 2
print(f'{{name}} is a full stack hacker.')
# {name} is a full stack hacker.

# 3
print(f'{{{name}}} is a full stack hacker.')
# {Yang} is a full stack hacker.

# 4
print(f'{{{{name}}}} is a full stack hacker.')
# {{name}} is a full stack hacker.

# 5
print(f'{{{{{name}}}}} is a full stack hacker.')
# {{Yang}} is a full stack hacker.

如上例所示,该变量是作为f-字符串的括号还是变量处理取决于其周围的括号数。如果您不知道这种奇怪的机制,则容易出现错误。

3.3 打印反斜线\

打印反斜线\很简单:只需使用双反斜线打印。但是不要将它们添加到 f 字符串表达式括号当中。

name = 'Yang'

print(f'\\{name}\\ is a full \\stack hacker.')
# \Yang\ is a full \stack hacker.

#错误的
print(f'{\\name\\} is a full \\stack hacker.')
# SyntaxError: f-string expression part cannot include a backslash

4. 小心打印字典值

将字典的值应用到 f 字符串中也容易出现错误。我们必须使用不同的引号来描述字典键和 f 字符串,如下所示。如果f字符串用双引号表示,那么变量里的字典键必须用单引号。

Hacker = {'name': 'Yang'}

print(f"{Hacker['name']} is a hacker")
# Yang is a hacker
print(f'{Hacker["name"]} is a hacker')
# Yang is a hacker
print(f'{Hacker['name']} is a hacker')
# 语法错误 SyntaxError: invalid syntax
print(f"{Hacker["name"]} is a hacker")
# 语法错误 SyntaxError: invalid syntax

如上所示,如果我们对键名和 f 字符串都使用相同的单引号或双引号, Python 会对我们的代码感到困惑, 从而报错。

5. 正确处理多行 F 字符串

为了使我们的代码更易读,有必要使用多行书写一长串字符。但如果是 f 字符串,不要忘记在每行之前添加f。

ame = 'Yang'

# 错误方式
print(f"{name} is a hacker."
      "{name} is also a top writer."
      "{name} writes on Medium."
      )
# Yang is a hacker.{name} is also a top writer.{name} writes on Medium.

# 正确方式
print(f"{name} is a hacker."
      f"{name} is also a top writer."
      f"{name} writes on Medium."
      )
# Yang is a hacker.Yang is also a top writer.Yang writes on Medium.

6. 像大师一样显示日期和时间

如果我们需要打印日期或时间,f 字符串将再次告诉我们它是多么方便:

from datetime import datetime
today = datetime.today()
print(f"Today is {today}")
# Today is 2023-11-12 15:59:30.284947
print(f"Today is {today:%B %d, %Y}")
# Today is November 12, 2023
print(f"Today is {today:%m-%d-%Y}")
# Today is 11-12-2023

如上例所示,在 f 字符串的帮助下,我们可以使用我们任何喜欢的格式打印日期或时间。

7. 评估 F 字符串内的表达式

当我第一次知道 f 字符串时, 我简直不敢相信:我们可以在 f 字符串内运行 Python 表达式。如果是真的,还算是字符串吗?

我仔细阅读了 PEP 498,终于明白了:

F 字符串提供了一种将表达式嵌入字符串字面的方法。需要注意的是,f 字符串实际上是在运行时间评估的表达方式,而不是恒定的值。

因此,f 字符串与普通字符串不同,此功能赋予它更大的能力。例如,我们可以在它里面运行一个显示时间的功能。

from datetime import datetime

print(f"Today is {datetime.today()}")
# Today is 2021-07-31 18:20:48.956829
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值