Substring Detection? Pythonically?
Fredrik Lundh
effbot at telia.com
Wed Oct 4 17:10:51 EDT 2000
Huaiyu Zhu wrote:
> BTW, why isn't there a string.match method, like re.match. That would mean
>
> filter('th'.match, list)
filter(re.compile("th").match, list)
in 2.0, there's also a startswith method, but it works
the other way around:
filter(lambda s: s.startswith("th"), list)
or if you prefer:
[s.startswith("th") for s in list]
> It would also be more efficient if the strings in list are long.
regular expressions are faster than you may think (at least
in 1.6 and 2.0). using a 200-word list and 2.0b2:
re.findall (Matcher class): 1.8 ms
filter re.match: 2.0 ms
filter startswith: 2.6 ms
comprehension startswith: 3.1 ms
filter string find: 6.5 ms
ymmv, of course...
</F>
More information about the Python-list
mailing list