当我尝试为“encoded.append("i")”行运行此代码时,我不断收到此错误:
属性错误:“str”对象没有属性“append”
我无法弄清楚为什么列表不会 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 = ''.join(encoded)
当然它没有属性“append”。
由于您在一个循环迭代中执行此操作,因此在下一次迭代中您将使用 str 而不是列表...
关于Python-属性错误: 'str' object has no attribute 'append' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878301/