[Python-ideas] adding a trim convenience function

Erick Tryzelaar idadesub at users.sourceforge.net
Wed Mar 5 21:45:17 CET 2008


I find that when I'm normalizing strings, I end up writing this a lot:

sites = ['www.google.com', 'http://python.org', 'www.yahoo.com']
new_sites = []
for site in sites:
  if site.startswith('http://'):
    site = site[len('http://'):]
  new_sites.append(site)

But it'd be much nicer if I could use a convenience function trim that
would do this for me, so I could just use a comprehension:

def ltrim(s, prefix):
  if s.startswith(prefix):
    return s[len(prefix):]
  return s

sites = ['www.google.com', 'http://python.org', 'www.yahoo.com']
sites = [ltrim(site, 'http://') for site in sites]

Would there be any interest to add this helper function, as well as an
"rtrim" and "trim", to the str class?

-e



More information about the Python-ideas mailing list