[Python-ideas] String Subtraction

Bruce Leban bruce at leapyear.org
Fri Oct 15 06:40:00 CEST 2010


Your code operates differently for "test blah,this". My code produces "test
,this" while yours produces "test this". Eliding multiple separators is
perhaps more useful when sep=' ' but I used commas because they're easier to
see.

An alternative design removes one separator either before or after a removed
string (but not both). That would work better for an example like this:

>>> remove('The Illuminati fnord are everywhere fnord.', 'fnord', sep=' ')
'The Illuminati are everywhere.'

Neither version of this may have sufficient utility to be added to standard
library.

--- Bruce
http://www.vroospeak.com
http://j.mp/gruyere-security



On Thu, Oct 14, 2010 at 8:22 PM, Dj Gilcrease <digitalxero at gmail.com> wrote:

> On Thu, Oct 14, 2010 at 7:45 PM, Bruce Leban <bruce at leapyear.org> wrote:
> > 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'
> >   """
>
> Could be written as
>
> def remove(string, sub, max_remove=-1, sep=None):
>    if sep:
>        sub = sub + sep
>    return string.replace(sub, '', max_remove)
>
> t = 'test,blah,blah,blah,this'
> print(remove(t, 'blah'))
> print(remove(t, 'blah', 2))
> print(remove(t, 'blah', sep=','))
> print(remove(t, 'blah', 2, ','))
> print(remove('foo(1)blah(2)blah(3)bar', 'blah', 1))
>
>
> Dj Gilcrease
>  ____
> ( |     \  o    ()   |  o  |`|
>   |      |      /`\_/|      | |   ,__   ,_,   ,_,   __,    ,   ,_,
> _|      | |    /      |  |   |/   /      /   |   |_/  /    |   / \_|_/
> (/\___/  |/  /(__,/  |_/|__/\___/    |_/|__/\__/|_/\,/  |__/
>          /|
>          \|
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20101014/f36d7ec5/attachment.html>


More information about the Python-ideas mailing list