我们不能检查一个值是否以字符串开头?
我有一个包含以下内容的词典:
my_dict = {'category': 'failure', 'logged_product': 'log_prd1', 'product': 'prd1', 'backlog_month_done': None,'TDC': <__main__.TDC object at 0x010F47D0>}
for attr, value in my_dict.items() :
if value.startswith('<__main') :
#removeit
为什么它与键有效而不是有价值?我该怎么做 ? 任何帮助将不胜感激
我收到错误:
AttributeError: 'NoneType' object has no attribute 'startswith'
答案 0 :(得分:7)
startswith
method is available for string objects,因此看起来attr
是一个字符串,但value
不是。
在您的修改中,您的某个值看似None
。要解决此问题,您应该在my_dict
:
'backlog_month_done': None
到此:
'backlog_month_done': ''
您还可以检查value
是否为字符串类型:
for attr, value in my_dict.items() :
if not isinstance(value, basestring):
continue
if value.startswith('<__main') :
#removeit
答案 1 :(得分:1)
如果value.startswith('&lt; __ main'):
此代码可能旨在查找<__main__.TDC object at 0x010F47D0>
,但它不起作用,因为您的dict
包含None
值,而您看到的<__main__.TDC object at 0x010F47D0>
仅仅是一个文本repr
对象的表示,但它不是字符串。
如果您确定自己真的需要这样的异类dict
,那么您应该根据isinstance
(或type
)的内容进行过滤。
for attr, value in my_dict.items() :
if not isinstance(value, basestring) :
continue # if you really want to remove it, use del my_dict[attr] here instead
答案 2 :(得分:0)
问题出现是因为my_dict['backlog_month_done']
是None
。
您可以使用if:
中的额外条件来解决此问题my_dict = {'category': 'failure', 'logged_product': 'log_prd1', 'product': 'prd1', 'backlog_month_done': None,'TDC': <__main__.TDC object at 0x010F47D0>}
for attr, value in my_dict.items() :
if value and value.startswith('<__main'):
#removeit
但是,我怀疑这会做你期望的,因为TDC
中my_dict
的值不是字符串:它是你复制并粘贴{{}的类的实例1}},所以你可能会收到像
repr
您可以通过选中AttributeError: 'TDC' object has no attribute 'startswith'
是value
:
str
然而,我怀疑那不是你想要的。如果要检查值是否是TDC的实例,则需要将for attr, value in my_dict.items() :
if isinstance(value, str) and value.startswith('<__main'):
#removeit
作为参数传递给TDC
:
isinstance
或者,如果您确定要删除以“&lt; __ main”开头的任何内容(甚至是repr),您需要确保获得该项目的字符串。在这种情况下,您可能希望使用for attr, value in my_dict.items() :
if isinstance(value, TDC):
#removeit
函数,因为经常重载repr
以返回自定义值。
str