Python-属性错误: 'str' object has no attribute 'append'

标签 python string list append

当我尝试为“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/

相关文章:

excel - 字符串加密/解密

python - 如何将字符串转换为时间戳进行比较?

Python如何找到列表中的最大元素

python - 如何对具有不同顺序的字符串列表进行排序?

Python:向变量添加换行符

python - Pandas 中的数据框列转置

python - 如何在流式查询中使用 MLlib 模型(失败并显示 "Field "功能“不存在。”)?

python - python 中更快的方法

java - java中按字符比较两个字符串

android - AdapterView 不支持 UnsupportedOperationException : addView(View, LayoutParams)