[Python-ideas] new format spec for iterable types
Paul Moore
p.f.moore at gmail.com
Wed Sep 9 16:41:19 CEST 2015
On 9 September 2015 at 15:32, Wolfgang Maier
<wolfgang.maier at biologie.uni-freiburg.de> wrote:
> Well, here it is:
>
> def unpack_format (iterable, format_spec=None):
> if format_spec:
> try:
> sep, element_fmt = format_spec.split('|', 1)
> except ValueError:
> raise TypeError('Invalid format_spec for iterable formatting')
> return sep.join(format(e, element_fmt) for e in iterable)
>
> usage examples:
>
> # '0.00, 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00'
> '{}'.format(unpack_format(range(10), ', |.2f'))
>
> # '0.001.002.003.004.005.006.007.008.009.00'
> '{}'.format(unpack_format(range(10), '|.2f'))
>
> # invalid syntax
> '{}'.format(unpack_format(range(10), '.2f'))
Honestly, it seems to me that
def format_iterable(it, spec, sep=', '):
return sep.join(format(e, spec) for e in it)
# '0.00, 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00'
format_iterable(range(10), '.2f')
# '0.001.002.003.004.005.006.007.008.009.00'
format_iterable(range(10), '.2f', sep='')
is perfectly adequate. It reads more clearly to me than the "sep|fmt"
syntax does, as well.
Paul
More information about the Python-ideas
mailing list