None in string formatting

R

rodney.maxwell

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

Is there a reason it maps to 'None'? I had expected ''.
 
S

Steven Bethard

Was doing some string formatting, noticed the following:


'None'

Is there a reason it maps to 'None'? I had expected ''.

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
 
J

Jorge Godoy

Was doing some string formatting, noticed the following:

'None'

Is there a reason it maps to 'None'? I had expected ''.

How would know, then, if there was no value at all or if it was an empty
string?
 
S

Scott David Daniels

Jorge said:
How would know, then, if there was no value at all or if it was an empty
string?

If you want the other effect, you can always do:

"%s" % (x or '')

--Scott David Daniels
(e-mail address removed)
 
S

Steve Holden

Jorge said:
How would know, then, if there was no value at all or if it was an empty
string?
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
 
E

Erik Max Francis

Was doing some string formatting, noticed the following:

'None'

Is there a reason it maps to 'None'? I had expected ''.

Because %s just calls str on the arguments, and str(None) == 'None'.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top