Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is null in python [duplicate]

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.

like image 783
Sandeep Krishnan Avatar asked Feb 14 '13 13:02

Sandeep Krishnan


2 Answers

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.

like image 88
Óscar López Avatar answered Oct 19 '22 07:10

Óscar López


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"
like image 44
mgilson Avatar answered Oct 19 '22 07:10

mgilson