当我尝试为“ encoded.append(“ i”)“行运行此代码时,我一直收到此错误:
AttributeError:'str'对象没有属性'append'
我无法弄清楚列表为什么不附加字符串。我相信问题很简单,谢谢您的帮助。
def encode(code, msg):
'''Encrypts a message, msg, using the substitutions defined in the
dictionary, code'''
msg = list(msg)
encoded = []
for i in msg:
if i in code.keys():
i = code[i]
encoded.append(i)
else:
encoded.append(i)
encoded = ''.join(encoded)
return encoded
>>> encoded =["d","4"]
>>> encoded="".join(encoded)
>>> print (type(encoded))
<class 'str'> #It's not a list anymore, you converted it to string.
>>> encoded =["d","4",4] # 4 here as integer
>>> encoded="".join(encoded)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
encoded="".join(encoded)
TypeError: sequence item 2: expected str instance, int found
>>>
如您所见,您的列表在此处转换为字符串"".join(encoded)
。并且append
是列表的方法,而不是字符串。这就是为什么您会收到该错误。同样,当您看到encoded
列表中是否有一个整数元素时,您会看到,TypeError
因为您不能join
对整数使用method。最好您再次检查所有代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句