different ways to strip strings

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Feb 27 17:21:24 EST 2006


On Mon, 27 Feb 2006 13:28:44 -0500, rtilley wrote:

> s = ' qazwsx '
> 
> # How are these different?
> print s.strip()
> print str.strip(s)

s.strip() strips white space from the start and end of string s. That is
standard object-oriented behaviour: you have an instance, s, and you call
its method, strip.

str.strip(s) is a little more tricky, but not much. str is the built-in
type for strings. Due to historical reasons, Python types and
user-definable classes are slightly different, but at the level we're
discussing here, you can imagine there is no difference.

In effect, you can think of str.strip(s) as calling the strip method
of the class (technically type) str, with s as the first argument. That is
equivalent to calling the strip method of the instance s with no arguments.


> Do string objects all have the attribute strip()? 

Yes, via inheritance. That is, each string object doesn't have a copy of
each method (strip, split, join, etc.) as that would be wasteful. The
same goes for all objects in Python, including ints, floats, lists,
as well as custom classes.

Python's inheritance rules mean that:

object_instance.method()

and 

object_type.method(object_instance) 

are equivalent.



> If so, why is str.strip() needed? 

Because that is the machinery by which string objects get the attribute
strip.


> Really, I'm just curious... there's a lot  don't fully understand :)

Gazing into my crystal ball, I'm going to answer your next question before
you answer it. Use the form s.strip() in preference to str.strip(s). It is
easier to read, faster, and generates smaller code.


-- 
Steven.




More information about the Python-list mailing list