strip() using strings instead of chars

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Jul 11 14:28:17 CEST 2008

Christoph Zwerschke a écrit :
> In Python programs, you will quite frequently find code like the
> following for removing a certain prefix from a string:
> if url.startswith('http://'):
>     url = url[7:]

DRY/SPOT violation. Should be written as :

  prefix = 'http://'
  if url.startswith(prefix):
      url = url[len(prefix):]


> My problem with this is that it's cumbersome and error prone to count
> the number of chars of the prefix or suffix.

cf above

> If you want to change it
> from 'http://' to 'https://', you must not forget to change the 7 to 8.
> If you write len('http://')  instead of the 7, you see this is actually
> a DRY problem.

cf above

> Things get even worse if you have several prefixes to consider:
> if url.startswith('http://'):
>     url = url[7:]
> elif url.startswith('https://'):
>     url = url[8:]
> You can't take use of url.startswith(('http://', 'https://')) here.

for prefix in ('http://', 'https://'):
     if url.startswith(prefix):
         url = url[len(prefix):]

For most complex use case, you may want to consider regexps, 
specifically re.sub:

 >>> import re
 >>> pat = re.compile(r"(^https?://|\.txt$)")
 >>> urls = ['', '', '', 
 >>> [pat.sub('', u) for u in urls]
['', '', '', 'file://tata']

Not to dismiss your suggestion, but I thought you might like to know how 
to solve your problem with what's currently available !-)

More information about the Python-list mailing list