new string function suggestion

Steven D'Aprano steve at
Mon Jun 13 10:25:31 CEST 2005

On Mon, 13 Jun 2005 07:05:39 +0000, Andy wrote:

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

If chop is analogous to strip, then they shouldn't raise exceptions if the
strings do not start with the prefix or suffix.

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

Any time you are writing the same piece of code over and over again, you
should refactor it out as a function in your module, or even in a special
"utility functions" module:

def lchop(s, prefix):
    if s.startswith(prefix): return s[len(prefix):]
    raise ValueError("Substring doesn't begin with prefix.")
    # or just return s if you prefer

and then call them whenever you need them.


More information about the Python-list mailing list