[Python-ideas] adding a trim convenience function

Tal Einat taleinat at gmail.com
Wed Mar 5 23:59:07 CET 2008

Erick Tryzelaar wrote:
> 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?

I'm against adding this as a string method, or even a a function in the stdlib.

I've done a lot of text processing with Python and have hardly ever
needed something like this. If you think this would be useful often, a
good way to convince this list is to show some examples of how it
could improve code in the standard library, noting how common they

In general, having a lot of string methods is very harmful because it
makes learning Python a longer and more confusing process.
Furthermore, this functionality is very simple and easy to implement,
I just thought of 3 different ways [1] to implement this function in a
simple, readable one-liner. For these reasons, unless you can show
that this will be very useful very often, I'm against.

- Tal

ltrim = lambda item, to_trim,: re.sub('^' + to_trim, '', item)
ltrim = lambda item, x: item[0 if not item.startswith(x) else len(x):]
ltrim = lambda item, to_trim: ''.join(item.split(to_trim, 1))

More information about the Python-ideas mailing list