[Tutor] creating the equivalent of string.strip()
Ricardo Aráoz
ricaraoz at gmail.com
Wed Oct 3 12:56:22 CEST 2007
Ian Witham wrote:
>
> On 10/3/07, *Alan Gauld* <alan.gauld at btinternet.com
> <mailto:alan.gauld at btinternet.com>> wrote:
>
>
> "Ricardo Aráoz" <ricaraoz at gmail.com <mailto: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)
>
You are right Ian. It's an extra "s[-1].isspace()" (and a jump) for
each leading whitespace, so though it works yours is still better. Don't
know why didn't see it :(, perhaps because I took code from the previous
post and did a quick fix. :( (and blushing in shame)
More information about the Tutor
mailing list