不能对字符串执行列表操作:>>> 'string'.append('addition')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'str' object has no attribute 'append'
如果支持添加,则只能向数据结构中添加某些内容:>>> li=['string']
>>> li.append('addition')
>>> li
['string', 'addition']
您要获取由与另一个字符串关联的字符串组成的dict:dictio = {"Object": "Computer"}
把它当作一个列表添加进去。与上述问题相同:>>> dictio["Object"].append("Mouse")
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'str' object has no attribute 'append'
怎么办?如果dict中的对象是一个字符串,则它需要是一个列表才能附加到它。
您可以先测试:>>> if isinstance(dictio["Object"], list):
... dictio["Object"].append('Mouse')
... else:
... dictio["Object"]=[dictio["Object"]]
... dictio["Object"].append('Mouse')
...
>>> dictio
{'Object': ['Computer', 'Mouse']}
或者试着去面对失败:try:
dictio["Object"].append("Mouse")
except AttributeError:
dictio["Object"]=[dictio["Object"]]
dictio["Object"].append("Mouse")