Python 3.6 中带元组的格式化字符串文字

Formatted string literals in Python 3.6 with tuples

使用 str.format() 我可以使用元组访问参数:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')

'a, b, c'

>>> t = ('a', 'b', 'c')
>>> '{0}, {1}, {2}'.format(*t)

'a, b, c'

但是有了前缀为 'f' (f-strings) 的新格式化字符串文字,我该如何使用元组?

f'{0}, {1}, {2}'.(*t)  # doesn't work

您的第一个 str.format() 调用是具有 3 个参数的常规方法调用,那里没有涉及元组。您的第二个调用使用 * splat 调用语法; str.format() 调用接收到 3 个单独的参数,它不关心那些来自元组。

使用 f 格式化字符串不使用方法调用,因此您不能使用任何一种技术。 f'..' 格式化字符串中的每个槽都作为常规 Python 表达式执行。

您必须直接从元组中提取值:

f'{t[0]}, {t[1]}, {t[2]}'

或者首先将元组扩展为新的局部变量:

a, b, c = t
f'{a}, {b}, {c}'

或者干脆继续使用str.format()。您没有使用f'..'格式化字符串,这是该语言的新的附加功能,而不是替代品str.format().

来自PEP 498 -- Literal String Interpolation

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.