简体   繁体   中英

Formatted string literals in Python 3.6 with tuples

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' (f-strings), how can I use tuples?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM