[Tutor] beginsWith multiple prefixes

Kent Johnson kent37 at tds.net
Thu Dec 25 14:20:31 CET 2008


2008/12/25 Alan Gauld <alan.gauld at btinternet.com>:

> 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.

It's an appealing idea but the extra step of wrapping strings in
MyString kind of takes the shine off of it. For example something like
this is awkward:
for d in os.listdir():
  d = MyString(d)
  if d.beginswith(...):

Some languages allow you to extend a built-in class, this technique
works better there.

Kent


More information about the Tutor mailing list