Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a custom string method

Tags:

python

How do you add a custom method to a built-in python datatype? For example, I'd like to implement one of the solutions from this question but be able to call it as follows:

>>> s = "A   string  with extra   whitespace"
>>> print s.strip_inner()
>>> A string with extra whitespace

So how would I define a custom .strip_inner() string method?

like image 345
mwolfe02 Avatar asked Dec 23 '10 14:12

mwolfe02


2 Answers

You can't. And you don't need to.

See Extending builtin classes in python for an alternative solution. Subclassing is the way to go here.

like image 123
Tim Pietzcker Avatar answered Oct 18 '22 21:10

Tim Pietzcker


The built-in classes such as str are implemented in C, so you can't manipulate them. What you can do, instead, is extend the str class:

>>> class my_str(str):
...     def strip_inner(self):
...         return re.sub(r'\s{2,}', ' ', s)
... 
>>> s = my_str("A   string  with extra   whitespace")
>>> print s.strip_inner()
A string with extra whitespace
like image 20
moinudin Avatar answered Oct 18 '22 21:10

moinudin