I’m trying to add 1 word/string to the back of the sentence ‘Afterall , what affects one family ‘.
Using the append method, it either returns ‘None’ if I append directly to the list or it will return an error ‘AttributeError’ if I append to the string. May I know how do I add the word/string to the back of the sentence?
S1 = 'Afterall , what affects one family ' Insert_String = 'member' S1_List = ['Afterall', ',', 'what', 'affects', 'one', 'family'] print(type(S1_List)) print(type(Insert_String)) print(type(S1)) print(S1_List) print(Insert_String) print(S1) print(S1_List.append(Insert_String)) print(S1.append(Insert_String)) Output <type 'list'> <type 'str'> <type 'str'> ['Afterall', ',', 'what', 'affects', 'one', 'family'] member Afterall , what affects one family None AttributeErrorTraceback (most recent call last) <ipython-input-57-2fdb520ebc6d> in <module>() 11 12 print(S1_List.append(Insert_String)) ---> 13 print(S1.append(Insert_String)) AttributeError: 'str' object has no attribute 'append'
Advertisement
Answer
The difference here is that, in Python, a “list” is mutable and a “string” is not — it cannot be changed. The “list.append” operation modifies the list, but returns nothing. So, try:
S1_List.append(Insert_String) print(S1_List) print(S1 + Insert_String)