searching for the number of occurences of a string

James Stroud jstroud at
Mon Mar 6 02:37:45 CET 2006

M.N.A.Smadi wrote:
> 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?
> what about if that string was say a 0 with leading and trailing white 
> spaces, would that be any different?
> thanks
> moe smadi

Some pieces:

To read every line in a file:

afile = open(filename)
for aline in afile:

To see if a string contains another string, try

if another_string() in astring:

If you need regular expressions, see the re module.

For instance:

import re
regex = re.compile(r'(?:\s+0\s+)|\(XYZ\)')

print'   0   ').group()
print' (XYZ) abc').group()

   print 'yep'
   print 'nope'

That should be everything you could possibly need. Its up to you to put 
it all together.

James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

More information about the Python-list mailing list