python 中的 f"{x}" 和 "{}".format(x) 有什么区别?

What's the difference between f"{x}" and "{}".format(x) in python?

我是 python 的新手,我只想知道这些示例之间的区别。 执行速度有什么不同吗?

我什么时候使用其中一个而不是另一个?

x: int = 64
print(f"Your Number is {x}")

x: int = 64
txt = "Your Number is {}"
print(txt.format(x))

提前致谢!

从技术上讲,没有区别。建议使用 f-string 格式,因为它较新:它是在 Python 3.6 中引入的。 RealPython explains f-stringsstr.format().

使用 f-strings 语法不那么冗长。假设您有以下变量:

first_name = "Eric"
last_name = "Idle"
age = 74
profession = "comedian"
affiliation = "Monty Python"

这就是格式化 str.format() 语句的方式。

print(("Hello, {name} {surname}. You are {age}. " + 
       "You are a {profession}. You were a member of {affiliation}.") \
       .format(name=first_name, surname=last_name, age=age,\
               profession=profession, affiliation=affiliation))

使用格式化字符串,它大大缩短了:

print(f"Hello {first_name} {last_name}. You are {age}" +
      f"You are a {profession}. You were a member of {affiliation}.")

不仅如此:格式化字符串提供了很多巧妙的技巧,因为它们是在运行时计算的:

>>> name="elvis" # note it is lowercase
>>> print(f"WOW THAT IS {name.upper()}")
'WOW THAT IS ELVIS'

这也可以在 str.format(...) 语句中完成,但 f-strings 使它更简洁、更简单。另外,您还可以在花括号内指定 formatting

>>> value=123
>>> print(f"{value=}")
'value = 123'

通常你应该写成print("value = {number}".format(number=value))。此外,您还可以评估表达式:

>>> print(f"{value % 2 =}")
'value % 2 = 1`

还有格式化数字:

>>> other_value = 123.456
>>> print(f"{other_value:.2f}") # will just print up to the second digit
'123.45'

和日期:

>>> from datetime.datetime import now
>>> print(f"{now=:%Y-%m-%d}")
'now=2022-02-02'

Python f-strings 已在 3.6 中添加。因此,如果您需要与早期版本兼容,您应该考虑使用 format() 。否则,使用 f-strings.

在 macOS 12.1 运行 3 GHz 10 核英特尔至强 W 和 Python 3.10.2 上,f-strings 明显更快 (~60%)

嗯,我个人一直使用 f 字符串,除非我处理浮点数或类似的东西,需要特定的格式,那时候使用 .format 更合适。

但是如果您不处理需要特定格式的文本,您应该使用 f 字符串,它更易于阅读。