[Tutor] beginsWith multiple prefixes
Alan Gauld
alan.gauld at btinternet.com
Thu Dec 25 12:40:22 CET 2008
"Emad Nawfal (عماد نوفل)" <emadnawfal at gmail.com> wrote
>> >> I want a function that acts like the startswith method, but can
>> >> take
>> >> multiple prefixes.
>> Above does a lot more work than necessary. Try:
>>
>> def beginsWith(word, listname):
>> for prefix in listname:
>> if word.startswith(prefix):
>> return True
You could also make this a method of a subclass of string if you
prefer:
class MyString(str):
def beginswith(self, prefixes):
for prefix in prefixes:
if self.startswith(prefix):
return prefix
Now you can create instances of MyString that will have all
the regular vstring methiods plus the new beginswith():
s = MyString("Welcome to my world")
if s.beginswith(["Welcome", "Hello","Howdy"]):
print "It's friendly"
Which looks more consistent.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list