[Tutor] creating the equivalent of string.strip()

wesley chun wescpy at gmail.com
Sun Sep 30 10:02:05 CEST 2007


> > I'm not sure how to proceed.  My biggest stumbling
> > block is how to detect the leading and trailing
> > whitespace.
>
> Use indexing.
> Try using a while loop.
> Or maybe two?
>
> And strings have an isspace method...

unfortunately, the isspace() string method only returns True if all
chars in the string are whitespace chars and False otherwise, so
that's a bummer.

on the other hand, the string module also has an attribute called
string.whitespace that contains all (valid/recognized) whitespace
characters with which you can compare individual characters of your
string with.

an alternative (yet possibly more complex) solution can use regular expressions.

you can also "cheat" and read the source code for the *strip() methods
and just duplicate them in Python. ;-)

regardless of what method you use, you should recognize that strings
cannot be modified (immutable), meaning that you will have to create a
new string (with all the whitespace removed).

good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list