Python中的append为什么使用出错?

代码这样写是对的:
n = ["Michael", "Lieberman"]
# Add your function here
def join_strings(words):
result=""
for i in range(len(words)):
result+=words[i]#第6行,这里如果修改了
return result
print join_strings(n)
但是我把第6行写为result.append(word[i])就报错:
Traceback (most recent call last):
File "python", line 9, in <module>
File "python", line 6, in join_strings
AttributeError: 'str' object has no attribute 'append'
为什么?哪里用得不对?谢谢!

Python中的append使用出错是由于设置错误,具体解决步骤如下:

1、在对应的python项目中新建一个文件,导入numpy和pandas,使用DataFrame()方法创建一个7乘以7的矩阵。

2、保存代码并直接使用python运行,可以在控制台查看到矩阵。

3、使用矩阵s1,调用iloc()方法获取对应序号的列元素。

4、再次保存代码并运行python文件,可以看到星期和数据构成的矩阵。

5、接着调用numpy模块中的append()方法,使用ignore_index属性。

6、结果出现了报错,修改python代码为s1.append(),查看结果即可。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-21
append将元素添加到已有list的末尾,多用在for.in循环,比如
str1=[]
for i in range(5):
str1.append(i)

print str1
输出为[0, 1, 2, 3, 4]

如果有str2=[9, 8, 7]

str1.append(str2)
则str1=[0, 1, 2, 3, 4, [9, 8, 7]]是将str2作为整个元素添加到str1

与之类似的有一个extend方法,与append不同,它是将list元素逐个添加到已有的list中,比如
str3=['a', 'b']
str3.extend(str2)
则str3=['a', 'b', 9, 8, 7]
第2个回答  2014-08-17
你的result是个字符串,字符串没有append这个方法。。如果是list之类的可以使用。
第3个回答  2015-08-29
list.append(一个元素)如果你添加多个元素就出错了呗。
第4个回答  推荐于2018-02-27
字符串没有append方法,将result改为=[]本回答被提问者和网友采纳
相似回答