如何检查Python中的字符串是否为null

25 投票
2 回答
128297 浏览
提问于 2025-04-17 15:53

我有一个叫做 cookie 的值,它是通过 Python 的 POST 请求返回的。
我需要检查这个 cookie 的值是否为空或者是无效的(null)。
所以我需要一个函数或者表达式来用在 if 条件里。
我该如何在 Python 中做到这一点呢?
举个例子:

if cookie == NULL

if cookie == None

附注:cookie 是存储这个值的变量。

2 个回答

5

在Python中,如果一个序列是空的,使用bool(sequence)会返回False。因为字符串也是一种序列,所以这个方法也适用:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"
28

试试这个:

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

上面的代码考虑了字符串是 None 或者只包含空格的情况。

撰写回答