[Python-ideas] String Subtraction (original) (raw)
Dj Gilcrease digitalxero at gmail.com
Fri Oct 15 05:22:59 CEST 2010
- Previous message: [Python-ideas] String Subtraction
- Next message: [Python-ideas] String Subtraction
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 || | | /
_/| | | ,__ ,, ,, , , ,,
| | | / | | |/ / / | |/ / | / _|/
(/___/ |/ /(,/ |/|/_/ |/|/_/|/,/ |/
/|
|
- Previous message: [Python-ideas] String Subtraction
- Next message: [Python-ideas] String Subtraction
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]