将字符串追加到列表/string返回'None'或'AttributeError:'str'对象在python中没有属性'append'

2024-10-05 11:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在“毕竟,什么影响一个家庭”这句话的后面加上一个单词/字符串

使用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'

Tags: 字符串stringtype单词familywhatonelist
2条回答

字符串数据类型是不可变的,并且没有append()方法。您可以尝试执行字符串连接:

old_string = old_string + new_string

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

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

相关问题 更多 >

    热门问题