searching for the number of occurences of a string

marek.rocki at marek.rocki at
Mon Mar 6 02:44:49 CET 2006

> hi;
> say i have a text file with a string ( say '(XYZ)') and I want to find
> the number of line where this string has occured. What is the best way
> to do that?

I would suggest:

# Read file contents
lines = file('filename.txt').readlines()
# Extract first line number containing 'XYZ' string
[(i, l) for (i, l) in enumerate(lines) if 'XYZ' in l][0][0]

Best regards,

More information about the Python-list mailing list