[Python-ideas] Briefer string format

Eric V. Smith eric at trueblade.com
Tue Jul 21 00:05:21 CEST 2015

On 7/20/2015 5:29 PM, Bruce Leban wrote:
> On Mon, Jul 20, 2015 at 1:20 PM, Eric V. Smith <eric at trueblade.com
> <mailto:eric at trueblade.com>> wrote:
>     So:
>     f'api:{sys.api_version} {a} size{sys.maxsize}'
>     would become either:
>     f'api:{.api_version} {} size{.maxsize}'.format(sys, a, sys)
>     or
>     f'api:{0.api_version} {1} size{0.maxsize}'.format(sys, a)
> Or: f'api:{} {} size{}'.format(sys.api_version, a, sys.maxsize)
> Note that format strings don't allow variables in subscripts, so
> f'{a[n]}'  ==>   '{}'.format(a['n'])

Right. But why re-implement that, instead of making it:

I've convinced myself (and maybe no one else) that since you want this:
f'{a[0]} {b[c]}'
being the same as:
'{} {}'.format(a[0], b['c'])

that it would be easier to make it:
'{[0]} {[c]}'.format(a, b)

instead of trying to figure out that the numeric-looking '0' gets
converted to an integer, and the non-numeric-looking 'c' gets left as a
string. That logic already exists in str.format(), so let's just
leverage it from there.

It also means that you automatically will support the subset of
expressions that str.format() already supports, with all of its
limitations and quirks. But I now think that's a feature, since
str.format() doesn't really support the same expressions as normal
Python does (due to the [0] vs. ['c'] issue). And it's way easier to
explain if f-strings support the identical syntax as str.format(). The
only restriction is that all parameters must be named, and not numbered
or auto-numbered.


More information about the Python-ideas mailing list