Dr. Phillip M. Feldman a écrit :
Bruno- You've made some excellent suggestions, and I'm always grateful for the opportunity to learn.
Glad to know I've been of any help !-)
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).'
Might be a bit more helpful (for the programmer using your function) to specify what 's' actually is. Also, the recommanded way to raise exceptions is to use the 'call' syntax, ie:
if not isinstance(s,(str,unicode)): raise TypeError("'s' must be a str or unicode, got '%s'" % type(s))
if not isinstance(open,(str,unicode)) or not isinstance(close,(str,unicode)): raise TypeError, '`open` and `close` must be strings (str or unicode).'
Mmmm.... I still wonder why you wouldn't accept a tuple or list of chars here.
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
wrt/ readability, it might be better to put the break statement on it's own line - but you can probably count this one as more of a personnal preference than a guideline !-)
# 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
Steven (D'Aprano) posted a possibly interesting implementation. Might be worth timeit'ing both.
-- http://mail.python.org/mailman/listinfo/python-list