[Python-ideas] new format spec for iterable types

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Sep 9 13:56:53 CEST 2015


On 9 September 2015 at 03:37, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> Oscar Benjamin writes:
>
>  > 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>)
>
> I thought about a colon, but that loses if the objects are times.  I
> guess that kills '/' and '-', too, since the objects might be dates.
> Of course there may be a tricky way to use these that I haven't
> thought of, or they could be escaped for use in <fmt>.

You can use the * at the start of the format element (before the first
colon). It can then imply that there will be two colons to separate
the three parts with any further colons part of fmt e.g.:

    '{*<expr>:<sep>:<fmt>}'.format(...)

So then you can have:

    >>> '{*numbers: :.1f}'.format(numbers)
    '1.0, 2.0, 3.0'

    >>> '{*times:, :%H:%M}'.format(times)
    '12:30, 14:50, 22:39'

--
Oscar


More information about the Python-ideas mailing list