[Tutor] Customized endswith/startswith version
kent37 at tds.net
Wed Aug 10 13:11:44 CEST 2005
Michael Janssen wrote:
> On 8/10/05, Negroup - <negroup at gmail.com> wrote:
>>how to modify startswith in order to make it accept a list instead of
>>a simple string?
>>[valid for valid in f.readlines() if valid.startswith(['abc', '123', 'ff5'])]
> the easy way is not to use the string method startwith but write your
> own function. So it looks like:
> [valid for valid in f.readlines() if startswith(valid, ['abc', '123', 'ff5'])]
> (I suppose you have your fun, writing a startswith-function for yourself?)
Besides the obvious way to write this function (checking each item in the list using startswith()) you can use a regular expression to do this:
> The hard way is to subclass from str and ovewrite the default
> startswith function (or add your own function). Whilst subclassing
> isn't hard, here it can be, because strings are immutable types, which
> means that a new string is created ervery time we "mutate" one. Which
> in turn means that you have to know how to subclass from immutable
> types (using __new__ instead of __init__ and things like that I can't
> remember and allways have a hard time to figure it out again). And
> then you might want to subclass your file-object so that it spit out
> strings of your own class?
You don't want to do this. The problem is that it's hard to get the behaviour you want. For example if you have class MyString and you do
'abc' + MyString('def')
you probably want the result to be a MyString but it won't be.
Some languages (Ruby and Objective-C at least) let you modify built-in classes like str by adding methods, but AFAIK Python doesn't allow that.
More information about the Tutor