0

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'
0

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

The string data type is immutable and does not have an append() method. You could try to perform string concatenation:

old_string = old_string + new_string

1 Comment

You could also use the augmented assignment operator: old_string += new_string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.