Python“不是None”返回None

时间:2015-02-13 16:44:25

标签: python null iteration

我正在迭代一些JSON对象,该对象的某些值为null。我试图将这些值存储在另一个对象中,并用空字符串替换null。但似乎"不是没有"正在回归"无"。 resource [key]应该是一个字符串或一个空字符串,但是它打印"无"

def sanitize_resource(self, *args):
    resource = {}
    for key, value in args[0].iteritems():
        resource[key] = str(value) if value is not None else ''
        print resource[key]
    return resource

args [0]

的示例
{"Resource Name":"Alexander","Contact Name":null,"Contact Email":null,"Primary Phone":"(828) 632","Primary Phone Ext":null,"Alternate Phone":null,"Alternate Phone Ext":null,"TTY":null,"Website URL":"http://url.org/locations/alexander/","Website Tiny URL":null,"Website Name":null,"Email":"live@url.org","Street Address":"260 Road","Street Address 2":null,"City":"Taylor","State":"FC","Postal Code":12345,"Description":null,"Category":null,"Tags":null,"Notes":null,"Services":null,"Longitude":null,"Latitude":null,"Thumbnail":null}

1 个答案:

答案 0 :(得分:4)

您没有None个对象。您有字符串 "None"

您可以使用repr()检测差异,而不是直接打印对象:

print repr(value)

字符串将打印出引号。

演示:

>>> value = None
>>> print repr(value)
None
>>> str(value) if value is not None else ''
''
>>> value = "None"
>>> print repr(value)
'None'
>>> str(value) if value is not None else ''
'None'