[TriZPUG] [triangle-zpug] how to match strings in python

Bradley A. Crittenden brad.crittenden at gmail.com
Fri Apr 3 00:52:14 CEST 2009


On Apr 2, 2009, at 17:57 , David Handy wrote:
>
> # The easy way
> import os
> i = len(os.path.commonprefix([string_1, string_2]))


Hey, that's great.  I had no idea that was hidden in os.path.

Their implementation is pretty cool, too:

def commonprefix(m):
     "Given a list of pathnames, returns the longest common leading  
component"
     if not m: return ''
     s1 = min(m)
     s2 = max(m)
     n = min(len(s1), len(s2))
     for i in xrange(n):
         if s1[i] != s2[i]:
             return s1[:i]
     return s1[:n]

m is a list of strings.  I hadn't considered using min/max on a list  
like this but doing so makes the function much more flexible.

This was a good discussion.  Thanks everyone.

--Brad



More information about the TriZPUG mailing list