string.count issue (simple)
Alex Martelli
aleax at aleax.it
Fri Aug 29 10:31:21 EDT 2003
Halfdan Holger Knudsen wrote:
> ok first off: Has the string.count function been replaced in python 2.2
> (as compared to 1.5)?m And second:
>
> I need this in relation to a stringsearch program
> assuming a text file has been loaded into allLines and word contains the
> string you're searching for I want to count all occurences of the search
> string the following should do it (but doesn't - please disregard any
> missing colons or such this has not been copy/pasted):
>
> count = 0
>
> for eachLine in allLines:
> if eachLine.find(word) > -1:
> count = count + eachLine.count(word, beg=0, end=len(eachLine)
Method count does not take keyword arguments. Besides, the ones you're
specifiying are redundant, and the if's condition is double work.
> print eachLine
> print count
I would recode this as:
count = 0
for eachLine in allLines:
countOnLine = eachLine.count(word)
if countOnLine:
count = count + countOnLine
print eachLIne
print count
> what am I missing - it only outputs the nubmer of lines (as if the count
> statement had been count = count + 1)
Hard to explain, since the code you're posting (with the keyword
arguments) can't possibly be the one you're running.
Alex
More information about the Python-list
mailing list