[Python-ideas] String Subtraction

Bruce Leban bruce at leapyear.org
Fri Oct 15 01:45:18 CEST 2010


Here's a useful function along these lines, which ideally would be
string.remove():

def remove(s, sub, maxremove=None, sep=None):
  """Removes instances of sub from the string.

  Args:
    s: The string to be modified.
    sub: The substring to be removed.
    maxremove: If specified, the maximum number of instances to be
        removed (starting from the left). If omitted, removes all instances.
    sep: Optionally, the separators to be removed. If the separator appears
        on both sides of a removed substring, one of the separators is
removed.

  >>> remove('test,blah,blah,blah,this', 'blah')
  'test,,,,this'
  >>> remove('test,blah,blah,blah,this', 'blah', maxremove=2)
  'test,,,blah,this'
  >>> remove('test,blah,blah,blah,this', 'blah', sep=',')
  'test,this'
  >>> remove('test,blah,blah,blah,this', 'blah', maxremove=2, sep=',')
  'test,blah,this'
  >>> remove('foo(1)blah(2)blah(3)bar', 'blah', 1)
  'foo(1)(2)blah(3)bar'
  """

  processed = ''
  remaining = s
  while maxremove is None or maxremove > 0:
    parts = remaining.split(sub, 1)
    if len(parts) == 1:
      return processed + remaining
    processed += parts[0]
    remaining = parts[1]
    if sep and processed.endswith(sep) and remaining.startswith(sep):
      remaining = remaining[len(sep):]
    if maxremove is not None:
      maxremove -= 1
  return processed + remaining

--- Bruce
Latest blog post:
http://www.vroospeak.com/2010/10/today-we-are-all-chileans.html<http://www.vroospeak.com>
Learn how hackers think: http://j.mp/gruyere-security



On Thu, Oct 14, 2010 at 3:16 PM, spir <denis.spir at gmail.com> wrote:

> On Thu, 14 Oct 2010 17:23:11 -0400
> Mike Meyer <mwm-keyword-python.b4bdba at mired.org> wrote:
>
> > The problem isn't that it's non-intuitive (there's only one intuitive
> > interface, and it's got nothing to do with computers), it's that there
> > are a wealth of "intuitive" meanings.
>
> Maybe have string.erase(sub,n) be a "more intuitive" shortcut for
> string.replace(sub,'',n)?
>
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
>
> spir.wikidot.com
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20101014/326eeb5d/attachment.html>


More information about the Python-ideas mailing list