[Tutor] Help Python String Search

John Fouhy john at fouhy.net
Tue Oct 7 00:36:54 CEST 2008


2008/10/7 Deitemeyer, Adam R <Adam.R.Deitemeyer at boeing.com>:
> I'm a beginner Python user and I have simple python issue I can't seem to
> solve.  I want to do a truth test on a string to see if a another string is
> contained within it.  I found that typically the re module has the methods
> to accomplish this.  However, every string I'm searching begins with a
> metacharacter.  For example: if the string '*I need *help' contains the word
> 'help' then true, else false..  Any advice you can provide would be great.

The presence of metacharacters shouldn't be a problem with regular
expressions; you can just "escape" them by putting a backslash (\)
before the character.

However ... your problem is sufficiently simple that you don't need
regular expressions.  The 'in' operator will do it for you:

>>> strings = ['I need help', 'This string does not contain the word', 'I no longer need help']
>>> for s in strings:
...   if 'help' in s:
...     print s
...
I need help
I no longer need help
>>>

If you are worried about case sensitivity, you can use the string
method .lower():

>>> 'help' in 'One HeLP twO'
False
>>> 'help' in 'One HeLP twO'.lower()
True
>>>

HTH!

-- 
John.


More information about the Tutor mailing list