Equivalent string.find method for a list of strings

Fredrik Lundh fredrik at pythonware.com
Fri Apr 8 16:13:06 EDT 2005


"jeremit0" <jeremit0 at gmail.com> wrote:
>I have read a text file using the command
>
> lines = myfile.readlines()
>
> and now I want to seach those lines for a particular string.  I was hoping there was a way to 
> "find" that string in a similar way as searching simply a simple string.  I want to do something 
> like
>
> lines.find.('my particular string')
>
> Is there a module that already exists that allows me to do this or will I have to created my own 
> method?

are you looking for a line that's equal to "my particular string", or a list that
*contains* "my particular string".

if the former, use

    index = lines.index("my particular string\n") # note the trailing newline

if the latter, you have to loop over the lines, and call the find method on each
one of them (alternatively, if all you want to know if "my particular string" is
anywhere in the file, just load the *entire* file using myfile.read(), and use find
on the entire file)

</F> 






More information about the Python-list mailing list