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

Alan Gauld alan.gauld at btinternet.com
Wed Oct 3 01:29:07 CEST 2007

"Ricardo Aráoz" <ricaraoz at gmail.com> wrote

> So as not to copy strings many times :
> while s[0].isspace() :
>    while s[-1].isspace() :
>        del s[-1]
>    del s[0]

Sorry, it won;t work. Strings are immutable.
However you can keep a track of the indexes of the
first and last non space characers and use slicing
if the copying seems to be a problem...

first,last = 0,-1

while s[first].isspace():
    first += 1
while s[last].isspace()
    last -= 1
return s[first:last]

There might be an off-by-one error in the slice, its untested...

Alan g.

More information about the Tutor mailing list