Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 303
Trimax Avatar asked Aug 04 '16 09:08

Trimax


People also ask

What is a formatted string literal in Python?

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.

Does Python 3.5 have F-strings?

Well, f-strings are only available since Python 3.6.


1 Answers

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.

like image 92
Martijn Pieters Avatar answered Oct 11 '22 22:10

Martijn Pieters