[Tutor] Grep equiv.

amoreira@mercury.ubi.pt amoreira@mercury.ubi.pt
Thu, 31 Aug 2000 16:26:13 +0100


Hello!

Wes Bateman wrote:
> 
> Hello all:
> 
> Sorry if this is a question I should have figured out on my own.

no problem.


> Is there a nice, easy, fast way of saying "if this
> line/string/variable/array/whatever contains 'xxx' then do 'something'"

There are several ways. Check out the string module and the functions
string.find() and string.index():

>>> import string
>>> string.find('Hello, Ze','Z')
7
>>> string.find('Hello, Ze','lo')
3
>>> string.find('Hello, Ze','H')
0
>>> string.find('Hello, Ze','W')
-1

string.index() is more or less the same but returns an error if no match
is found, instead of the silent -1 returned by string.find.  There is
also the re module, with more advanced pattern matching possibilities.

Hope it helps
So long!
Ze