finding an element in a string
Stephen R Laniel
steve at laniels.org
Mon Jun 25 16:20:39 EDT 2007
On Mon, Jun 25, 2007 at 04:09:50PM -0400, Miguel Oliveira wrote:
> But that, obviously, will only respond "good" when one writes "fine". I was
> looking for a way for the program to respond "good" to any sentence that would
> contain the word "fine" in it.
What you want is a regular-expression match. Are you
familiar with regexes? The relevant Python documentation is
here (for the module 're'):
http://docs.python.org/lib/module-re.html
though I find it's not particularly easy reading. The
Friedl book recommended in there is the canonical source
about regexes, and it is indeed a great book. You should
read some manpages first, though. Just google for 'regular
expressions' and you'll find all that you need.
In the meantime, what you want is something like
if re.search( r'fine', x ):
# things one does if the user said 'fine'
Alternately, you could just use rfind():
http://docs.python.org/lib/string-methods.html
but regexes are a good tool to get to know. They're overused
(particularly in Perl), but this is just the sort of task
they're good for.
--
Stephen R. Laniel
steve at laniels.org
Cell: +(617) 308-5571
http://laniels.org/
PGP key: http://laniels.org/slaniel.key
More information about the Python-list
mailing list