[Tutor] Customized endswith/startswith version
Negroup -
negroup at gmail.com
Wed Aug 10 14:41:21 CEST 2005
2005/8/10, Michael Janssen <mi.janssen at gmail.com>:
> 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')]
[cut]
> The hard way is to subclass from
[cut]
> And then you might want to subclass your file-object so that it spit out
> strings of your own class?
Thanks for your reply.
My solution is:
foo.py
class MyStr(str):
def myStartsWith(self, options=[]):
if (type(options) != type([]) or not options):
return 'Error'
else:
for option in options:
if self.startswith(option):
return self
return False
class MyFile(file):
def get_valid(self, options):
return [MyStr(valid).myStartsWith(options) for valid in
self.readlines() if MyStr(valid).myStartsWith(options)]
codes.txt
ff6
#ff5
123is a test
abc another test
abc last one
>>> from foo import MyStr, MyFile
>>> f = MyFile('codes.txt')
>>> f.get_valid(['abc', '123', 'ff5'])
['123is a test\n', 'abc another test\n', 'abc last one\n']
More information about the Tutor
mailing list