【问题标题】:Python - AttributeError: 'str' object has no attribute 'append'Python - AttributeError:'str'对象没有属性'append'
【发布时间】:2015-03-08 19:42:23
【问题描述】:

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

【问题讨论】:

  • 你的 cod 中没有"decoded.append("i")":,你的意思是"encoded.append("i")":??
  • encoded = ''.join(encoded)背后的逻辑是什么

标签: python string list append


【解决方案1】:

您在此处将编码设置为字符串:

encoded = ''.join(encoded)

当然它没有“附加”属性。

由于您是在一次循环迭代中执行此操作,因此在下一次迭代中您将使用 str 而不是 list...

【讨论】:

    【解决方案2】:

    您的字符串转换行位于else 子句下。从条件和 for 循环中取出它,以便它是对encoded 所做的最后一件事。就目前而言,您在 for 循环的中途转换为字符串:

    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)
    
    # after all appends and outside for loop
    encoded = ''.join(encoded)
    return encoded
    

    【讨论】:

    • 如果encoded 列表有一个整数元素,它将抛出TypeError。这不是这个问题的解决方案。
    • 没有说明此函数将提供的输入类型。这也不适用于许多其他类型,而不仅仅是整数。问题是“为什么?”,而不是“这应该是什么?”,因此这是完全合理的,即使它并不理想。
    【解决方案3】:
    >>> 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 方法。最好再次检查所有代码。

    【讨论】:

      【解决方案4】:

      由于 else 语句中的第二个表达式,您会收到错误消息。

          ''.join(encoded) returns a string that gets assigned to encoded
      

      因此编码现在是字符串类型。 在第二个循环中,您在 if/else 语句中都有 .append(i) 方法,该方法只能应用于列表而不是字符串。

      你的 .join() 方法应该出现在你返回之前的 for 循环之后。

      如果上面的文字看起来不正确,我很抱歉。这是我的第一篇文章,我仍在尝试弄清楚它是如何工作的。

      【讨论】:

        猜你喜欢
        • 2015-02-17
        • 2018-05-16
        • 1970-01-01
        • 2018-06-22
        • 2015-08-16
        • 2017-08-14
        • 1970-01-01
        • 2013-11-05
        • 2018-12-01
        相关资源
        最近更新 更多