pythonstringlistappend

Python - AttributeError: 'str' object has no attribute 'append'


I keep receiving this error when I try to run this code for the line "encoded.append("i")":

AttributeError: 'str' object has no attribute 'append'

I cannot work out why the list won't append with the string. I'm sure the problem is very simple Thank you for your help.

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

Solution

  • >>> 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
    >>> 
    

    As you see, your list is converted to a string in here "".join(encoded). And append is a method of lists, not strings. That's why you got that error. Also as you see if your encoded list has an element as integer, you will see TypeError because, you can't use join method on integers. Better you check your all codes again.