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?
JavaScript
x
34
34
1
S1 = 'Afterall , what affects one family '
2
Insert_String = 'member'
3
S1_List = ['Afterall', ',', 'what', 'affects', 'one', 'family']
4
print(type(S1_List))
5
print(type(Insert_String))
6
print(type(S1))
7
8
print(S1_List)
9
print(Insert_String)
10
print(S1)
11
12
print(S1_List.append(Insert_String))
13
print(S1.append(Insert_String))
14
15
16
17
18
Output
19
20
<type 'list'>
21
<type 'str'>
22
<type 'str'>
23
['Afterall', ',', 'what', 'affects', 'one', 'family']
24
member
25
Afterall , what affects one family
26
None
27
AttributeErrorTraceback (most recent call last)
28
<ipython-input-57-2fdb520ebc6d> in <module>()
29
11
30
12 print(S1_List.append(Insert_String))
31
---> 13 print(S1.append(Insert_String))
32
33
AttributeError: 'str' object has no attribute 'append'
34
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:
JavaScript
1
4
1
S1_List.append(Insert_String)
2
print(S1_List)
3
print(S1 + Insert_String)
4