1

I have an object converted to a string using str(object). I would like to check, using the string, if I had a None object (in my case it would never be 'None' unless the object is None).

string = str(object) // object is None
if string is 'None' or string is str(None):
  // do something

The problem is the condition never passes. How can I check this case?

The same way str(None) is str(None) returns False. Why?

nhuon
  • 143
  • 1
  • 6
  • You've confused equality with identity. Try `string == 'None' or string == str(None)`. See http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs or http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – Robᵩ May 08 '14 at 03:22
  • Careful not to override the built in `object` constructor by using it as a variable name... – temporary_user_name May 08 '14 at 03:27
  • 1
    Do not use `object` as a variable name! `>:-(` – dawg May 08 '14 at 03:34

5 Answers5

3
if object is None:
    print("the object is None")
else:
    print("the object exists")
Edwan
  • 39
  • 7
2

Use

if string == 'None':
   # Do something.

Check out What is the semantics of 'is' operator in Python? for the meaning of 'is` in python.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

The string conversions of another object will in general not be the same object each time the conversion is made; it makes a new string each time. the is operator compares identity, not value. You want ==

>>> l = [1,2,3]
>>> str(l) is str(l)
False
>>> str(l) == str(l)
True
irh
  • 358
  • 2
  • 10
1

First of all, object is a pre-defined class, the common ancestor of all classes. However, it has nothing to do with your question.

After calling string = str(None), the variable string holds 'None', a python string. You can call type(string) # should be <type 'str'> to confirm it. To solve this issue, you can replace it with:

  • string == 'None'
  • string == str(None)
  • if object is None Matches None and nothing else.
  • if object Match all falsy values
clifflu
  • 71
  • 1
  • 6
1

Check for None with Nonetype any time you know None is a valid possibility. In fact, unless the return string you get passed in is the string value 'None', you should not design your app to check for this possibility with string comparisons anyway. Notwithstanding the is vs == operator differences.

tjborromeo
  • 156
  • 6