Checking if string starts with list element

Darrell Gallion darrell at dorb.com
Mon Aug 14 18:24:33 EDT 2000


No idea how fast or slow this is. I have a version of findall that returns
the group that hit as well as the match string. That would remove the inner
loop here.

import string, re
words=string.split("Hope this isn't full of holes")
wordsPat="(?im)(^"+string.join(words,".*?$)|(^")+".*?$)"
print 'Pat:', wordsPat
wordsPat=re.compile(wordsPat)

input="""
Hope may not be enough.
Work is full
Holes have been known to flow.
isn't this fun
"""
res=re.findall(wordsPat,input)
iRange=range(len(res[0]))
for x in range(len(res)):
    i = res[x]
    for y in iRange:
        if len(i[y]) > 0:
            print "Line: %4d %10s : %s"%(x, words[y], i[y])
            break

#output
Line:    0       Hope : Hope may not be enough.
Line:    1      holes : Holes have been known to flow.
Line:    2      isn't : isn't this fun


--Darrell

----- Original Message -----
From: "Simon Brunning" <SBrunning at trisystems.co.uk>

> I have a list of strings:
> romans = ['aqueduct', 'sanitation', 'roads', 'irrigation', 'medicine',
> 'education', 'wine', 'public baths', 'order']
>
> And I have a single string:
> us = 'wine, women and song.'
>
> I want to know whether my sting *starts with* one of the strings in my
list.
> The best that I can do is something like:
>
> for roman in romans:
>     if string.find(us, roman) == 0:
>         # do stuff
>         break
>
> The trouble is that in the code I'm writing, the list has a hundred or so
> elements, and it's running too slowly. Any suggestions?
>






More information about the Python-list mailing list