我试图在“毕竟,什么影响一个家庭”这句话的后面加上一个单词/字符串
使用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'
字符串数据类型是不可变的,并且没有
append()
方法。您可以尝试执行字符串连接:这里的区别在于,在Python中,“列表”是可变的,“字符串”不是可变的,它不能更改。“list.append”操作修改列表,但不返回任何内容。因此,请尝试:
相关问题 更多 >
编程相关推荐