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

Ian Witham witham.ian at gmail.com
Wed Oct 3 10:56:16 CEST 2007


On 10/3/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
> "Ricardo Aráoz" <ricaraoz at gmail.com> wrote
>
> >sorry, forgot a piece of the code :
> >
> >s = list(s)
> >while s[0].isspace() :
> >     while s[-1].isspace() :
> >         del s[-1]
> >     del s[0]
> > s = ''.join(s)
>
> It still won't work. Strings are immutable, you can't use del
> to delete a character. Try it.
>

Alan, he does convert to a list first and then rejoin to a string
afterwards, so using del is not the problem.

However, the script is still flawed.
The loop to delete trailing whitespace is nested within the loop to delete
the leading whitespace. The trailing whitespace loop only needs to be run
once, but it is currently being processed once for each leading space and
not at all if there are no leading spaces!
For instance, "  Myriad Harbor  " strips OK, but "Myriad Harbor  " does not.

The solution of course is to keep the two loops separate:

s = list(s)
while s[0].isspace() :
    del s[0]
while s[-1].isspace() :
    del s[-1]
s = ''.join(s)

Ian.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071003/a4d6f28c/attachment-0001.htm 


More information about the Tutor mailing list