[Tutor] Grep equiv.

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


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')
>>> string.find('Hello, Ze','lo')
>>> string.find('Hello, Ze','H')
>>> string.find('Hello, Ze','W')

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!