[Tutor] Customized endswith/startswith version

Michael Janssen mi.janssen at gmail.com
Wed Aug 10 12:23:30 CEST 2005


On 8/10/05, Negroup - <negroup at gmail.com> wrote:

> >>> f = open('codes.txt')
> >>> # valid codes starts with 'abc' or '123' or 'ff5'
> >>> [valid for valid in f.readlines() if valid.startswith('abc') or
> valid.startswith('123') or valid.startswith('ff5')]
> 
> This is just an example, in my application I don't need to check
> strings against a huge number of cases. If however it would happen,
> 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?)

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?

regards
Michael


More information about the Tutor mailing list