[Python-ideas] String Subtraction (original) (raw)
Bruce Leban bruce at leapyear.org
Fri Oct 15 06:40:00 CEST 2010
- Previous message: [Python-ideas] String Subtraction
- Next message: [Python-ideas] Fwd: stats module Was: minmax() function ...
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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, maxremove=-1, sep=None): if sep: sub = sub + sep return string.replace(sub, '', maxremove) 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>
- Previous message: [Python-ideas] String Subtraction
- Next message: [Python-ideas] Fwd: stats module Was: minmax() function ...
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]