[Tutor] advice on idiomatic python and re module question

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon May 17 18:27:49 EDT 2004



On Mon, 17 May 2004, Andrew Fant wrote:

> I had a feeling I was doing something stupid like calling the wrong
> method.  that will learn me to try and be more clever than I am.
> Either that or to not think in Fortran.


Hi Andrew,


Don't worry about it; people get tripped up by the confusing distinction
between match() and search().  In fact, it's a FAQ!  *grin*

http://www.amk.ca/python/howto/regex/regex.html#SECTION000720000000000000000

and everyone trips on it when they start using regexes in Python.  The
fact that everyone trips on it is a bad sign: I wonder how receptive folks
would be to rename match() to something verbose like
'search_from_start()'...


Anyway, if you are doing really simple patterns like:

> >> pattern1=re.compile('^#')
> >> pattern2=re.compile('eth0')

you might find it easier to use the string methods 'startswith()', as well
as the substring operator 'in':


###
>>> 'hello'.startswith('h')
True
>>> 'hello'.startswith('hola')
False
>>>
>>> 'll' in 'hello'
True
>>> 'ol' in 'hello'
False
###


We can find a list of the common string methods here:

    http://www.python.org/doc/lib/string-methods.html


Good luck to you!




More information about the Tutor mailing list