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

24,699

You set encoded to string here:

encoded = ''.join(encoded)

And of course it doesn't have attribute 'append'.

Since you're doing it on one of cycle iteration, on next iteration you have str instead of list...

Share:
24,699
Admin
Author by

Admin

Updated on January 11, 2020

Comments

  • Admin
    Admin over 4 years

    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
    
  • Admin
    Admin over 9 years
    If that encoded list has an integer element it will throw TypeError. It's not a solution for this question.
  • James
    James over 9 years
    Nothing was stated about the type of input this function would give. This also won't work with many other types, not simply integers. The question was "why?", not, "what should this be?", thus it's perfectly reasonable, even if it's not ideal.