Python "is not None" 返回 None
Python "is not None" returning None
我正在遍历一个 JSON 对象,该对象的某些值为 null。我试图将这些值存储在另一个对象中,并将 null 替换为空字符串。然而,似乎 "is not None" 正在返回 "None"。 resource[key] 应该是字符串或空字符串,但它正在打印 "None"
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
参数示例[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}
您没有 None
对象。你有 string "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'
我正在遍历一个 JSON 对象,该对象的某些值为 null。我试图将这些值存储在另一个对象中,并将 null 替换为空字符串。然而,似乎 "is not None" 正在返回 "None"。 resource[key] 应该是字符串或空字符串,但它正在打印 "None"
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
参数示例[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}
您没有 None
对象。你有 string "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'