Why is str(None) == 'None' and not an empty string?

Tim Delaney timothy.c.delaney at gmail.com
Thu Aug 29 16:59:51 EDT 2013


On 29 August 2013 20:43, Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Wed, Aug 28, 2013 at 6:21 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> > On Wed, 28 Aug 2013 01:57:16 -0700, Piotr Dobrogost wrote:
> >
> >> Hi!
> >>
> >> Having repr(None) == 'None' is sure the right thing but why does
> >> str(None) == 'None'? Wouldn't it be more correct if it was an empty
> >> string?
> >
> >
> > Why do you think an empty string is more correct? Would you expect
> > str([]) or str(0.0) or str({}) to also give an empty string?
> >
> >
> > I can't see any reason for str(None) to return the empty string.
>
> I've had many occasions where it would have been convenient for
> str(None) to return the empty string, e.g. when exporting tabular data
> that includes null values from a database to a spreadsheet.  Generally
> it's safe to just call str() on the data, except that I'd rather empty
> cells just be empty rather than spamming the word "None" all over the
> place, so I end up having to do something like (str(value) if value is
> not None else '') instead.  Not a major inconvenience, but enough to
> make me wonder if there could be a better way.
>

There is.

def format(value):
    if value is None:
        return ''

    return str(value)

print(format(value))

This also allows you to format other types differently e.g. only output 2
decimal places for non-integer numeric types.

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130830/861c97c4/attachment.html>


More information about the Python-list mailing list