how to convert string function to string method?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Dec 7 03:49:28 EST 2009


On Sun, 06 Dec 2009 22:47:48 -0800, Dr. Phillip M. Feldman wrote:

> I wrote a handy-dandy function (see below) called "strip_pairs" for
> stripping matching pairs of characters from the beginning and end of a
> string.  This function works, but I would like to be able to invoke it
> as a string method rather than as a function.  Is this possible?

Not exactly. You can subclass string and add such a method:

class MyString(str):
    def strip_pairs(self, ...):
        ...

but then you have to convert every string to a MyString before you use 
it. That way leads to madness.

Better to just use a function. Don't worry, you're allowed to mix 
functional and OO code :)


As for the function, I think we can re-write it to be a bit more 
Pythonic. We start with a helper function. (Since it's a one-liner, 
that's not strictly necessary.)


def bracketed_by(s, open, close):
    """Return True if string s is bracketed by open and close pairs."""
    # I'm too lazy to put proper error handling here...
    return s.startswith(open) and s.endswith(close)


# UNTESTED       
def strip_pairs(s, open='([{\'"', close=')]}\'"'):
    if len(open) != len(close):
        raise ValueError(
        "'open' and 'close' arguments must be equal length strings.")
    if not isinstance(s, basestring):
        # FIX ME: this wrongly fails on UserString arguments.
        raise TypeError('argument must be a string')
    pairs = zip(open, close)
    while any(bracketed_by(s, a, b) for (a,b) in pairs):
        s = s[1:-1]
    return s



The above is written for simplicity rather than efficiency -- for small 
strings, say, under a couple of megabytes, it is likely to be faster than 
a more "clever" algorithm. If you are routinely dealing with strings 
which are tens of megabytes in size, bracketed by dozens or hundreds of 
pairs of brackets, then the above may be a little slow. But for small 
strings, it will probably be faster than a routine which tries to be 
smarter at avoiding copying strings.



-- 
Steven



More information about the Python-list mailing list