2017-07-01 50 views
-3

我试图处理来自抽搐API的一些数据来检查线路是否是活的或不是从JSON名单像这样的字符串:检查的变量在python

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") 
+1

'如果rstatus是None:...' –

回答

2

当你看到印有“无”,这是告诉你RSTATUS不存在的Python的方式。它就像其他语言中的“null”一样。这不是一个字符串,它几乎没有。你可以这样做:

if rstatus is None: 
    foo 
else: 
    bar 

“没有”是这样做的首选方式。它比rstatus == none更快,更可接受。

希望这会有所帮助!

+0

明白了,谢谢! –

-2

很简单:

>>> 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... 
>>> 
+1

'如果状态不是None' – eandersson

+0

哇 - 不同的表达和即时downvotes。 – Mandraenke

+0

“蟒蛇之禅”中列出的第一条规则是“美丽胜于丑陋”。:) – eandersson