how to convert string function to string method?
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon Dec 7 03:46:30 EST 2009
Dr. Phillip M. Feldman a écrit :
> 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?
No. Basic type (strings/unicode, numerics, lists, tuples, dicts etc) are
not "opened" to monkeypatching. Partly for performance reasons, partly
to avoid the insanity that we've seen in the Ruby world where everyone
and it's little sisters extends basic types with tons of more or less
usefull and often conflicting features.
> def strip_pairs(s=None, open='([{\'"', close=')]}\'"'):
Why a default value of None for the first param ???
> """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.'
Please use proper exception types. Here you want a ValueError. Also, you
just dont care whether open and close are proper strings - any sequence
of characters would do.
> # 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
If s is None, it won't be a str or unicode instance, so the test is
redundant !-)
But anyway : if this function is supposed to operate on strings, don't
accept None (and even less provide it as default), and don't fail
silently - you should really raise a TypeError here IMHO.
> 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
HTH
More information about the Python-list
mailing list