[Tutor] beginsWith multiple prefixes

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Wed Dec 24 22:04:21 CET 2008


Hi Tutors,
I want a function that acts like the startswith method, but can take
multiple prefixes. As an amateur programmer, I came up with this one, and it
works fine, but my experience tells me that my solutions are not always the
best ones around. Can you please tell me what a better option might be:



def beginsWith(word, listname):
    count = 0
    x = range(len(word))
    for i in x:
        if word[:i] in listname:
            count+=1

            break

    if count > 0:
        return True
    else:
        return False


# main
text = "ana mary fify floor school security".split()

prefixes = ["an", "ma", "fi", "sec"]

for word in text:
    if beginsWith(word, prefixes):
        print(word+" (Match)")
    else:
        print(word)

#This produces the following:
IDLE 3.0      ==== No Subprocess ====
>>>
ana (Match)
mary (Match)
fify (Match)
floor
school
security (Match)
>>>

-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081224/e97c040d/attachment-0001.htm>


More information about the Tutor mailing list