Rajanikanth Jammalamadaka a écrit :
(top-post corrected - Please, Rajanikanth, learn to trim&quote properly, and by all means avoid top-posting)

On Wed, Jul 9, 2008 at 12:13 AM, Lamonte Harris <[EMAIL PROTECTED]> wrote:
Alright, basically I have a list of words in a file and I load each word
from each line into the array.

<OP>
I assume you meant 'list' ?
</OP>

Then basically the question is how do I
check if the input word matches multiple words in the list.

Say someone input "test", how could I check if that word matches these list
of words:

test
testing
tested

Out of the list of

Hello
blah
example
test
ested
tested
testing

I want it to loop then check if the input word I used starts any of the
words in the list so if I typed 'tes'

Then:

test
testing
testing

<OP>
I assume you meant:
 test
 tested
 testing
</OP>

would be appended to a new array.

> hi!
>
> Try this:
>
>>>> lis=['t','tes','test','testing']
>>>> [elem for elem in lis if re.compile("^te").search(elem)]

Using a regexp for this is total overkill. But please at least use the proper regexp, and use re.compile correctly:

exp = re.compile(r'^tes')
found = [word for word in lis if exp.match(word)]

But you just don't need a regexp for this - str.startswith is your friend:

words = ['Hello', 'blah', 'example', 'test', 'ested', 'tested', 'testing']
found = [word for word in words if word.starswith('tes')]
assert found == ['test', 'tested', 'testing']

HTH
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to