文件搜索功能不返回位置?
问题描述:
我正在测试给定文件的输入/输出。每个文件都包含字符串,我将在该文件中搜索's',并返回该文件中s的位置的有序列表。该功能没有给出位置,而是给出了整条线。为什么?文件搜索功能不返回位置?
这里是我的功能:
def locate(filename,s):
lookfor=s
new_list=[]
with open(filename) as my_file:
for num, line in enumerate(my_file):
if lookfor in line:
new_list.append(num)
new_list.sort()
return new_list
答
def locate(filename,s):
lookfor=s
new_list=[]
with open(filename) as my_file:
for num, line in enumerate(my_file,1):
if lookfor in line:
new_list.append(num)
new_list.sort()
return new_list
'排序()'工作** **就位。所以写两条语句:'new_list.sort()'和'return new_list'。 –
[为什么“返回list.sort()”返回无,不是列表?](http://stackoverflow.com/questions/7301110/why-does-return-list-sort-return-none-不在列表中) –
修复了重复。我做了两个陈述,但我仍然得到错误的输出。查看更新的问题。 –