如何在python中检查字符串是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14876316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string is null in python
提问by Sandeep Krishnan
I have a value cookie that is returned from a POST call using Python.
I need to check whether the cookievalue is empty or null.
Thus I need a function or expression for the if condition.
How can I do this in Python?
For example:
我有一个使用 Python 从 POST 调用返回的值 cookie。
我需要检查该cookie值是空还是空。因此,我需要一个用于 if 条件的函数或表达式。我怎样才能在 Python 中做到这一点?例如:
if cookie == NULL
if cookie == None
P.S. cookieis the variable in which the value is stored.
PScookie是存储值的变量。
采纳答案by óscar López
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 Noneor a sequence of white spaces.
以上考虑了字符串是None或一系列空格的情况。
回答by mgilson
In python, bool(sequence)is Falseif the sequence is empty. Since strings are sequences, this will work:
在蟒蛇,bool(sequence)是False如果序列是空的。由于字符串是序列,这将起作用:
cookie = ''
if cookie:
print "Don't see this"
else:
print "You'll see this"

