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 -- View this message in context: http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26673209.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list