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...
Author by
Admin
Updated on January 11, 2020Comments
-
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 over 9 yearsIf that
encoded
list has an integer element it will throwTypeError
. It's not a solution for this question. -
James over 9 yearsNothing 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.