25

I have a value cookie that is returned from a POST call using Python.
I need to check whether the cookie value is empty or null. Thus I need a function or expression for the if condition. How can I do this in Python? For example:

if cookie == NULL

if cookie == None

P.S. cookie is the variable in which the value is stored.

Joshua D. Boyd
  • 4,808
  • 3
  • 29
  • 44
Sandeep Krishnan
  • 465
  • 1
  • 6
  • 12

2 Answers2

28

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
5

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"
mgilson
  • 300,191
  • 65
  • 633
  • 696