how to convert string function to string method?

r0g aioe.org at technicalbloke.com
Mon Dec 7 03:37:47 EST 2009


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?
> 
> def strip_pairs(s=None, open='([{\'"', close=')]}\'"'):
>    """This function strips matching pairs of characters from the beginning
> and
>    end of the input string `s`.  `open` and `close` specify corresponding
> pairs
>    of characters, and must be equal-length strings.  If `s` begins with a
>    character in `open` and ends with the corresponding character in `close`,
>    both are removed from the string.  This process continues until no
> further
>    matching pairs can be removed."""
> 
>    if len(open) != len(close): raise Exception, \
>      '\'open\' and \'close\' arguments must be strings of equal length.'
> 
>    # If input is missing or is not of type `str` (or `unicode`), return
> None:
>    if s is None or not isinstance(s,(str,unicode)): return None
> 
>    while len(s) >= 2:
> 
>       # Check whether first character of `s` is in `open`:
>       i= open.find(s[0])
> 
>       # If `s` does not begin with a character from `open`, there are no
> more
>       # pairs to be stripped:
>       if i == -1: break
> 
>       # If `s` does not begin and end with matching characters, there are no
>       # more pairs to be stripped:
>       if s[-1] != close[i]: break
> 
>       # Strip the first and last character from `s`:
>       s= s[1:-1]
> 
>    return s


I've never tried it but I think it is possible to inject new methods
into existing classes, see...

http://www.daniel-lemire.com/blog/archives/2005/12/21/metaclass-programming-in-python/

Not sure how good an idea it would be though, I have heard it refered to
as "monkey patching" and I can imagine doing it to classes as
fundamental as the string class could have negative performace consequences.

Roger.



More information about the Python-list mailing list