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
Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol.
Well, f-strings are only available since Python 3.6.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With