【问题标题】:Checking a string in a variable in python在python中检查变量中的字符串
【发布时间】:2017-12-05 12:57:32
【问题描述】:

我正在尝试处理来自 twitch API 的一些数据,以检查频道是否来自这样的 json 列表中的直播:

import requests
import json

r = requests.get("http://some-api/api", params)

rdata = r.json()

rstatus = rdata["live"]

rstatus 为我返回“无”字符串以表示离线,否则它不会返回。所以我想要检查rstatus 是“None”还是与“None”字符串不同的东西。我试过这段代码但没有用:

if "None" in rstatus:
    print("Live")
else:
    print("Offline")

【问题讨论】:

  • if rstatus is None: ...

标签: python json string api


【解决方案1】:

很简单:

>>> status = None
>>> if status:
...   print "it live, status is not None"
... else:
...   print "too sad..."
...
too sad...
>>>

但 Python 的禅宗说,“显式优于隐式。”。测试状态是否为无:

>>> if not status == None:
...   print "it live, status is not None"
... else:
...   print "too sad..."
...
too sad...
>>>

【讨论】:

  • if status is not None
  • “Python之禅”中列出的第一条规则是“美胜于丑”。:)
【解决方案2】:

当您看到打印的“无”时,这是 Python 告诉您 rstatus 不存在的方式。这就像其他语言中的“null”。它不是一个字符串,它实际上什么都不是。你可以这样做:

if rstatus is None:
    foo
else:
    bar

'is None' 是首选的方法。它比rstatus == none 更快,更容易被接受。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2011-05-02
    相关资源
    最近更新 更多