[Python-ideas] new format spec for iterable types
Ron Adam
ron3200 at gmail.com
Wed Sep 9 18:59:38 CEST 2015
On 09/08/2015 09:37 PM, Stephen J. Turnbull 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>.
This seems to me to need a nested format spec. An outer one to format
the whole list, and an inner one to format each item.
f"foo {', '.join(f'{x:inner_spec}' for x in iter):outer_spec}"
Actually this is how I'd rather write it.
"foo " + l.fmap(inner_spec).join(', ').fstr(outer_spec)
But sequences don't have the methods to write it that way.
>>> l = range(10)
>>> "foo" + format(','.join(map(lambda x: format(x, '>5'), l)), '>50')
'foo 0, 1, 2, 3, 4, 5, 6, 7, 8, 9'
It took me a few times to get that right.
Cheers,
Ron
More information about the Python-ideas
mailing list