[Python-ideas] new format spec for iterable types

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Sep 8 20:42:22 CEST 2015


On 8 September 2015 at 19:15, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
> ATM the colon separates the part of the format element that is
> interpreted by the format method to find the formatted object from the
> part that is passed to the __format__ method of the formatted object.
> Perhaps an additional colon could be used to separate the separator
> for when the formatted object is an iterable so that
>
>      'foo {name:<fmt>:<sep>} bar'.format(name=<expr>)
>
> could become
>
>     'foo {_name} bar'.format(_name = '<sep>'.join(format(o, '<fmt>')
> for o in <expr>))
>
> The example would then be
>
>     >>> '{:.1f}, {:.1f:, }'.format(99, range(10))
>     '99.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0'

Except that obviously that wouldn't work because colon can be part of
the <fmt> string e.g. for datetime:

    >>> '{:%H:%M}'.format(datetime.datetime.now())
    '19:39'

So you'd need something before the colon to disambiguate. In which case perhaps

      'foo {*name:<sep>:<fmt>} bar'.format(name=<expr>)

meaning that if the * is there then everything after the second colon
is the format string.

Then it would be:

     >>> '{:.1f}, {*:, :.1f}'.format(99, range(10))
     '99.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0'

--
Oscar


More information about the Python-ideas mailing list