new string function suggestion
Andy
spam at be.gone
Mon Jun 13 03:05:39 EDT 2005
What do people think of this?
'prefixed string'.lchop('prefix') == 'ed string'
'string with suffix'.rchop('suffix') == 'string with '
'prefix and suffix.chop('prefix', 'suffix') == ' and '
The names are analogous to strip, rstrip, and lstrip. But the functionality
is basically this:
def lchop(self, prefix):
assert self.startswith(prefix)
return self[len(prefix):]
def rchop(self, suffix):
assert self.endswith(suffix)
return self[:-len(suffix]
def chop(self, prefix, suffix):
assert self.startswith(prefix)
assert self.endswith(suffix)
return self[len(prefix):-len(suffix]
The assert can be a raise of an appropriate exception instead. I find this
to be a very common need, and often newbies assume that the
strip/lstrip/rstrip family behaves like this, but of course they don't.
I get tired of writing stuff like:
if path.startswith('html/'):
path = path[len('html/'):]
elif s.startswith('text/'):
path = path[len('text/'):]
It just gets tedious, and there is duplication. Instead I could just write:
try:
path = path.lchop('html/')
path = path.lchop('text/')
except SomeException:
pass
Does anyone else find this to be a common need? Has this been suggested
before?
Andy
More information about the Python-list
mailing list