how to convert string function to string method?

Stephen Hansen apt.shansen at gmail.com
Mon Dec 7 02:20:36 EST 2009


On Sun, Dec 6, 2009 at 10:47 PM, Dr. Phillip M. Feldman <
pfeldman at verizon.net> 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?
>

No. String objects are immutable and you can not set new attributes/methods
on the type itself.

Really the best thing to do in this case is to just have this in an easy to
access library, and call it as a function and not a string method.

The only alternative is to create a string subtype which has a new method--
but that would require all the strings you're using to be this subclass.
E.g. you'd have to do MyString(regular_String) for each. This is really IMHO
unwieldy and not really worth the effort -- just put strip_pairs into a
library and call it as a function.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091206/875103fd/attachment.html>


More information about the Python-list mailing list