初学者问题:我应该使用fstring吗?

2024-09-30 01:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

你好

我对Python非常陌生,所以我有一个问题。 这两张照片产生相同的结果,至少对我来说,第一个版本看起来更可读。 我是否应该坚持使用f'版本,因为它以后会给我带来问题/性能更差/今天的python标准/? 或者,这仅仅是这些版本中的一个一致使用的问题

print('My first bycicle was a '+ bicycles[1])
print(f'My first bicycle was a {bicycles[1]})')

Tags: 版本标准my性能照片firstprintwas
1条回答
网友
1楼 · 发布于 2024-09-30 01:31:58

来自PEP498,一个致力于文字字符串插值的PEP(Python增强建议)

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is reallyan expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces. The expressions are replaced with their values.

这里的要点是突出显示的文本,这意味着由于CPython编译器内部实现了AST(抽象语法树),这使得它们的计算速度更快

此外,我认为它更具可读性,并且在字符串中包含更多变量的情况下,它提供了更好的可读性。使用此语法可以轻松执行多行字符串插值

例如:

f'''
    My first bicycle was a {bicycles[0]}
    It has color {bicycles[0]["color"]}
    and has {bicycles[0]["gears"]} gears.
'''

相关问题 更多 >

    热门问题