f-Strings 是从 Python 3.6 开始提供的,非常适用于字符串格式化。
>>> n='you'
>>> f'hello {n}, how are you?'
'hello you, how are you?'
阅读有关它们的更多信息,请参阅Python 3的f字符串:改进的字符串格式语法(指南)。我发现了一个有趣的模式:
Note that using triple braces will result in there being only single braces in your string:
>>> f"{{{74}}}" '{74}'
However, you can get more braces to show if you use more than triple braces:
>>> f"{{{{74}}}}" '{{74}}'
这正是情况所在:
>>> f'{74}'
'74'
>>> f'{{74}}'
'{74}'
现在,如果我们从两个 {
转移到三个,结果是相同的:
>>> f'{{{74}}}'
'{74}' # same as f'{{74}}' !
所以我们需要最多4个!({{{{
)才能得到两个括号作为输出:
>>> f'{{{{74}}}}'
'{{74}}'
为什么会这样?为什么两个大括号在Python中要求额外的一个大括号?
f"{{2+2}}"
和f"{{{2+2}}}"
的输出结果进行比较,可能会有所启发。它们分别是'{2+2}'
和'{4}'
。 - Kevinf'{2+2}'
返回4,f'{{2+2}}'
返回2+2,f'{{{2+2}}}'
返回{4},f'{{{{2+2}}}}'
返回{{2+2}}等等。这很合理,但初看有些令人困惑。 - fedorquif'{74}'
和f'74'
是一样的。 - kaya3str.format
也可以实现这个。 - Peilonrayzstr.format
例子吗?它显然是一样的x = 74;'{{x}}'.format(x=x);'{{{x}}}'.format(x=x)
->'{x}'
,'{74}'
。 - Peilonrayz