Formatted string literals in Python 3.6 with tuple

2019-09-14 16:36发布

问题:

With str.format() I can use tuples for accesing arguments:

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

'a, b, c'

or

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

'a, b, c'

But with the new formatted string literals prefixed with 'f' how can use tuples?

回答1:

Your first str.format() call is a regular method call with 3 arguments, there is no tuple involved there. Your second call uses the * splat call syntax; the str.format() call receives 3 separate individual arguments, it doesn't care that those came from a tuple.

Formatting strings with f don't use a method call, so you can't use either technique. Each slot in a f'..' formatting string is instead executed as a regular Python expression.

You'll have to extract your values from the tuple directly:

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

or first expand your tuple into new local variables:

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

or simply continue to use str.format(). You don't have to use an f'..' formatting string, this is a new, additional feature to the language, not a replacement for str.format().

From PEP 498 -- Literal String Interpolation:

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