[英]append string to list/string returns 'None' or 'AttributeError: 'str' object has no attribute 'append'' in python
I'm trying to add 1 word/string to the back of the sentence 'Afterall, what affects one family '.我正在尝试在句子“毕竟,什么影响一个家庭”的后面添加 1 个单词/字符串。
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.使用 append 方法,如果我将 append 直接返回到列表,它将返回“None”,或者如果将 append 发送到字符串,它将返回错误“AttributeError”。 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'
The difference here is that, in Python, a "list" is mutable and a "string" is not -- it cannot be changed.这里的区别在于,在 Python 中,“列表”是可变的,而“字符串”则不是——它无法更改。 The "list.append" operation modifies the list, but returns nothing.
“list.append”操作修改列表,但不返回任何内容。 So, try:
所以,试试:
S1_List.append(Insert_String)
print(S1_List)
print(S1 + Insert_String)
The string data type is immutable and does not have an append()
method.字符串数据类型是不可变的,并且没有
append()
方法。 You could try to perform string concatenation:您可以尝试执行字符串连接:
old_string = old_string + new_string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.