Substring Detection? Pythonically?

Fredrik Lundh effbot at telia.com
Wed Oct 4 15:48:08 EDT 2000


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