Issue
First timer here with really using files and I/O. I'm running my code through a tester and the tester calls the different files I'm working with through my code. So for this, I'm representing the file as "filename" below and the string I'm looking for in that file as "s". I'm pretty sure I'm going through the lines of the code and searching for the string correctly. This is what I have for that :
def locate(filename, s):
file= open(filename)
line= file.readlines()
for s in line:
if s in line:
return [line.count]
I'm aware the return line isn't correct. How would I return the number of the line that the string I'm looking for is located on as a list?
Solution
You can use enumerate
to keep track of the line number:
def locate(filename, s):
with open(filename) as f:
return [i for i, line in enumerate(f, 1) if s in line]
In case the searched string can be found from first and third line it will produce following output:
[1, 3]
Answered By - niemmi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.