首页 > 解决方案 > 将字符串附加到列表/字符串返回'None'或'AttributeError:'str'对象在python中没有属性'append''

问题描述

我正在尝试在句子“毕竟,什么影响一个家庭”的后面添加 1 个单词/字符串。

使用 append 方法,如果我直接附加到列表,它会返回“None”,或者如果我附加到字符串,它将返回错误“AttributeError”。我可以知道如何将单词/字符串添加到句子的后面吗?

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'

标签: pythonstringlistattributeerror

解决方案


这里的区别在于,在 Python 中,“列表”是可变的,而“字符串”不是——它不能更改。“list.append”操作修改列表,但不返回任何内容。所以,试试:

S1_List.append(Insert_String)
print(S1_List)
print(S1 + Insert_String)

推荐阅读