Substring Detection? Pythonically?

Stephen Hansen stephen at cerebralmaelstrom.com
Thu Oct 5 22:08:57 EDT 2000


LOL. I feel dumb. I don't really know precisely what is going on in that
acode, largely because I don't yet completely understand lamdba's and try
to avoid regexp's whenever possible, so don't exactly clearly understand
them either. :) I'm very impressed it's so easily -- and perfectly! -- doable
in eight lines. :)

I am also surprised that according to the numbers you posted in another
message that regexp's were that much faster then any of the other
solutions; i'm developing w/ 2.0b2 btw. :)

Thanks a bunch.

--S

In article <YPLC5.167$YU1.7871 at newsc.telia.net>, "Fredrik Lundh"
<effbot at telia.com> wrote:

> Stephen Hansen wrote:
>> Okay, say I have three different strings:
>> #1: they
>> #2: that
>> #3: tommy
>> 
>> And a user gives me a string -- 'the', I want it to match to 'they'.
>> Then say they give me a string, 'to', I want it to match to 'tommy'. A
>> string of 'th' or 't' is ambiguious, and i want a list returned,
>> ['they','that'] and ['they','that','tommy'] respectively.
> 
> import re, string
> 
> class Matcher:
>     def __init__(self, names):
>         self.names = string.join(map(lambda x: "{%s}" % x, names), "")
>     def find(self, name):
>         return re.findall("{(" + re.escape(name) + "[^}]*)}",
>         self.names)
> 
>>>> m = Matcher(("they", "that", "tommy")) m.find("the")
> ['they']
>>>> m.find("to")
> ['tommy']
>>>> m.find("th")
> ['they', 'that']
>>>> m.find("t")
> ['they', 'that', 'tommy']
>>>> m.find("x")
> []
> 
> (if you cannot do it in 8 lines of python, it's not worth doing)
> 
> </F>
> 
> <!-- (the eff-bot guide to) the standard python library:
> http://www.pythonware.com/people/fredrik/librarybook.htm
> -->
>



More information about the Python-list mailing list