[Tutor] beginsWith multiple prefixes

bob gailer bgailer at gmail.com
Thu Dec 25 00:04:37 CET 2008


Emad Nawfal (عماد نوفل) wrote:
> 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
Above does a lot more work than necessary. Try:
 
def beginsWith(word, listname):
    for prefix in listname:
       if word.startswith(prefix):
          return True
>
>
> # 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
> --------------------------------------------------------
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
Chapel Hill NC 
919-636-4239



More information about the Tutor mailing list