[Python-ideas] new format spec for iterable types
Stephen J. Turnbull
stephen at xemacs.org
Tue Sep 8 18:27:27 CEST 2015
Wolfgang Maier writes:
> But the proposed simple version saves me from mistakenly writing:
>
> '{}\t{}'.format(head, '\t'.join(data))
>
> when some of the elements in data aren't strings and I should have written:
>
> '{}\t{}'.format(head, '\t'.join(str(e) for e in data))
>
> , a mistake that I seem to never learn to avoid :)
(Note: I don't suffer from that particular mistake, so I may be
biased.) I think it's a nice trick but doesn't clear the bar for
adding to the standard iterables yet.
A technical comment: you don't actually need the '*' for myList
(although I guess you find it useful to get an error rather than line
noise as a separator if it isn't present?)
On the basic idea: if this can be generalized a bit so that
head = 99
data = range(10) # optimism!
s = '{:.1f}, {:.1f*, }'.format(head, data)
produces
s == '99.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0'
then I'd be a lot more attracted to it. I would think the simple
version is likely to produce rather ugly output if you have a bunch of
floats in data. (BTW, that string was actually generated with
'{:.2f}, {}'.format(99, ', '.join('{:.2f}'.format(x) for x in range(10)))
which doesn't win any beauty contests.)
Bikeshedding in advance, now you pretty much need the '*' (and have to
hope that the types in the iterable don't use it themselves!), because
'{:.1f, }' really does look like line noise! I might actually prefer
'|' (or '/') which is "heavier" and "looks like a separator" to me:
s = '{:.1f}, {:.1f|, }'.format(head, data)
Finally, another alternative syntax would be the same in the
replacement field, but instead of iterables implementing it, the
.format method would (using your syntax and example for easier
comparison):
s = '{}, {:*, }'.format(head, *data)
I'm afraid this won't work unless restricted to be the last
replacement field, where it just consumes all remaining positional
arguments. I think that restriction deserves a loud "ugh", but maybe
it will give somebody a better idea.
Steve
More information about the Python-ideas
mailing list