In Codio, there is a challenge to take a file, search for the number of times a string appears in it, then print that number. I was able to get the result using some suggestions, but I am still unclear on a few things.
The main question is, at what point is the loop searching for the substring S
? The count()
syntax that I see everywhere involves using the string to be searched, followed by the dot operator, and then the function with the substring we want to find as the parameter. It would look something like: P.count(S)
What confuses me is that the function is using line
in place of P
. So does this mean the function is searching line
for the substring? And if so, how does that work if line
is simply the counter variable for the for
loop? I just want to have a clearer understanding of how this function is working in this context to get me the correct count of times that substring S
appears in file P
.
import sys
P= sys.argv[1]
S= sys.argv[2]
# Your code goes here
f = open(P, 'r')
c = 0
for line in f.readlines():
c += line.count(S)
print(c)