【问题标题】:How to check if a string is null in python [duplicate]如何在python中检查字符串是否为空[重复]
【发布时间】:2013-01-30 08:13:39
【问题描述】:

我有一个使用 Python 从 POST 调用返回的值 cookie。
我需要检查cookie 值是空还是空。 因此,我需要一个 if 条件的函数或表达式。 我怎样才能在 Python 中做到这一点? 例如:

if cookie == NULL

if cookie == None

附: cookie 是存储值的变量。

【问题讨论】:

  • 你使用的是什么网络框架?
  • 您需要描述用于获取 cookie 值的函数:这​​将告诉我们要测试什么(None 值?仅空字符串?)。

标签: python string null


【解决方案1】:

试试这个:

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

以上考虑了字符串为None 或一系列空格的情况。

【讨论】:

  • cookie.isspace() 比使用strip 效率更高
  • @gnibbler 你是对的,我更新了我的答案。谢谢!
【解决方案2】:

在 python 中,如果序列为空,bool(sequence)False。由于字符串是序列,这将起作用:

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

【讨论】:

  • 如果你有 - cookie = "null" 然后 bool(cookie) 返回 True。
  • if cookieif cookie == "" 的功能有什么区别?
猜你喜欢
  • 2019-08-05
  • 1970-01-01
  • 2014-07-06
  • 2014-02-22
  • 1970-01-01
  • 2019-06-06
  • 2016-09-13
  • 2011-11-25
相关资源
最近更新 更多