[Tutor] String matching

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Nov 26 21:35:05 CET 2004



On Fri, 26 Nov 2004, Bernard Lebel wrote:

>  >>> mystring = 'helloworldmynameisbernardlebel'
>
>  >>> if not re.compile( 'bernard' ).match( mystring ) == None:
> ... 	print 'success'
>
> Well, nothing gets printed. Could anyone tell me how to achieve that
> simple type of matching?


Hi Bernard,

Oh, one more thing.  If you're just trying to see if a string is a
substring of another, then you might want to just say something like this:

###
if 'bernard' in mystring: ...
###


This is a simpler way to do a substring match.  In general, we can see if
one string is a substring of another by using the 'in' operator:

    if substring in anotherstring: ...


If we need to know where a substring matches in the larger string, then
there's a 'find()' string method that should do the trick.

###
>>> "this is a test".find("is")
2
###

Note that this find() method is only checking for substring matching: it
has no knowledge of words.  If we needed it to match the whole word, then
we'd probably need regular expressions:

###
>>> import re
>>> re.search(r'\bis\b', "this is a test").start()
5
###

But if we don't need the full power of regular expressions, then we may
prefer the simpler exact string matching that find() gives us.


Good luck!



More information about the Tutor mailing list