how to control formatting of a namedtuple in a list
Ned Batchelder
ned at nedbatchelder.com
Thu Nov 17 19:08:41 EST 2016
On Thursday, November 17, 2016 at 6:50:07 PM UTC-5, Boylan, Ross wrote:
> Thank you; I can confirm that overriding __repr__ makes the list display as I wanted.
>
> The decision to use repr inside the list seems very odd, given the context, namely formatting something for display or looking for a simple string representation. It seems more natural to me to use str or, if in a format, the default formatting all the way down. Is there a good reason it's repr?
I think of it as str is for customers, repr is for developers. Or, repr is
for nerds, str is for civilians, etc. If you print a list, then you will
get square brackets and commas separating the display. That is, you are
already getting a nerdy output. So the contents of the list are also
displayed in the nerdy way, with repr.
If you want a nice display of the contents, you also have to control the
display of the list itself, so you can do whatever you need, and use str
on the contents yourself.
--Ned.
More information about the Python-list
mailing list