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.

2
  • 1
    What web framework are you using? Commented Feb 14, 2013 at 13:52
  • You need to describe what function you use for getting your cookie value: this will tell us what to test for (None value? empty string only?). Commented Feb 14, 2013 at 14:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

cookie.isspace() is more efficient than using strip
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"

3 Comments

what if you have have - cookie = "null" then bool(cookie) return True.
what's the difference in functionality between if cookie and if cookie == ""?
Although the answer is valid for the grand majority of cases, the OP wanted to check if the string was None or empty (containing whitespace), e.g. ' ' or '\n\t'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.