None in string formatting

Discussion in 'Python' started by rodney.maxwell, Mar 8, 2005.

  1. Was doing some string formatting, noticed the following:
    'None'

    Is there a reason it maps to 'None'? I had expected ''.
     
    rodney.maxwell, Mar 8, 2005
    #1
    1. Advertisements

  2. Can you explain why you expected that? A few other examples that make
    me not expect what you do:

    py> '%s' % False
    'False'
    py> '%s' % []
    '[]'
    py> '%s' % {}
    '{}'
    py> '%s' % set()
    'set([])'

    All of the objects above evaluate to False in a boolean context like ''
    does, but they display a string appropriate to their type. Since None
    has it's own type (NoneType), I would expect similar behavior.

    STeVe
     
    Steven Bethard, Mar 8, 2005
    #2
    1. Advertisements

  3. rodney.maxwell

    Jorge Godoy Guest

    How would know, then, if there was no value at all or if it was an empty
    string?
     
    Jorge Godoy, Mar 8, 2005
    #3
  4. If you want the other effect, you can always do:

    "%s" % (x or '')

    --Scott David Daniels
     
    Scott David Daniels, Mar 8, 2005
    #4
  5. rodney.maxwell

    Steve Holden Guest

    Well, for that matter, how can you tell the difference between

    '%s' % False

    and

    '%s' % 'False'

    since both inevitably produce the same output.

    The bottom line is that you are trying to map the strings plus other
    values on to the strings, which means it's a mathematical certainty
    there will be ambiguities. It's just that you want *your* preferred
    ambiguities rather than what Python gives you.

    Suppose Python were to do what you want, how could you distinguish
    between the outputs for "" and None? Of course, at the moment the
    outputs for "None" and None are the same, but that just supports my
    assertion about the inevitability of ambiguities.

    regards
    Steve
     
    Steve Holden, Mar 8, 2005
    #5
  6. Because %s just calls str on the arguments, and str(None) == 'None'.
     
    Erik Max Francis, Mar 9, 2005
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.