searching for the number of occurences of a string

marek.rocki at wp.pl marek.rocki at wp.pl
Sun Mar 5 20:44:49 EST 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,
Marek




More information about the Python-list mailing list