how to convert string function to string method?

Dr. Phillip M. Feldman pfeldman at verizon.net
Mon Dec 7 22:07:47 EST 2009


Bruno- You've made some excellent suggestions, and I'm always grateful for
the opportunity to learn.  My revised code appears below.  Philllip

def strip_pairs(s, open='([{\'"', close=')]}\'"'):
   """
   OVERVIEW

   This function strips matching pairs of characters from the beginning and
   end of the input string `s`.  If `s` begins with a character in `open`
and
   ends with the corresponding character in `close` (see below), both are
   removed from the string. This process continues until no further matching
   pairs can be removed.

   INPUTS

   `open` and `close`: These arguments, which must be equal-length strings,
   specify matching start-of-scope and end-of-scope characters.  The same
   character may appear in both `open` and `close`; single and double quotes
   conventionally match themselves.  By default, `open` contains a left
   parenthesis, left square bracket, left curly bracket, single quote, and
   double quote), and `close` contains the corresponding characters."""

   if not isinstance(s,(str,unicode)):
      raise TypeError, '`s` must be a string (str or unicode).'

   if not isinstance(open,(str,unicode)) or not
isinstance(close,(str,unicode)):
      raise TypeError, '`open` and `close` must be strings (str or
unicode).'

   if len(open) != len(close): raise ValueError, \
     '\'open\' and \'close\' arguments must be equal-length strings.'

   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--tp26673209p26688035.html
Sent from the Python - python-list mailing list archive at Nabble.com.




More information about the Python-list mailing list