trying to match a string

John Machin sjmachin at lexicon.net
Sat Jul 19 23:07:10 CEST 2008


On Jul 20, 5:00 am, Andrew Freeman <alif... at gmail.com> wrote:
> Andrew Freeman wrote:
> > John Machin wrote:
> >> A couple of points:
> >> (1) Instead of search(r'^blahblah', ...) use match(r'blahblah', ...)
> >> (2) You need to choose your end-anchor correctly; your pattern is
> >> permitting a newline at the end:
>
> I forgot to change search to match. This should be better:
>
> def match(var):
>     if re.match(r'[LRM]*\Z', var):
>         return True
>     else:
>         return False

A bit wordy ...

if blahblah:
   return True
else:
   return False

can in total generality be replaced by:

return blahblah


>
> I was also thinking if you had a list of these items needing to be
> verified you could use this:

You could, but I suggest you don't use it in a job interview :-)

>  >>> l = ['LLMMRR', '00thLL', 'L', '\n']

(1) Don't use 'L'.lower() as a name; it slows down reading as people
need to fire up their mental parser to distinguish it from the result
of 3 - 2

>  >>> out = []
>  >>> map(lambda i: match(i)==False or out.append(i), l)
(2) Read PEP 8
(3) blahblah == False ==> not blahblah
(4) You didn't show the output from map() i.e. something like [None,
True, None, True]
(5) or out.append(...) is a baroque use of a side-effect, and is quite
unnecessary. If you feel inexorably drawn to following the map way,
read up on the filter and reduce functions. Otherwise learn about list
comprehensions and generators.

>  >>> print out
> ['LLMMRR', 'L']
>

Consider this:

>>> import re
>>> alist = ['LLMMRR', '00thLL', 'L', '\n']
>>> zeroplusLRM = re.compile(r'[LRM]*\Z').match
>>> filter(zeroplusLRM, alist)
['LLMMRR', 'L']
>>> [x for x in alist if zeroplusLRM(x)]
['LLMMRR', 'L']
>>>

Cheers,
John



More information about the Python-list mailing list