[Tutor] creating the equivalent of string.strip()
ricaraoz at gmail.com
Wed Oct 3 02:29:19 CEST 2007
Alan Gauld wrote:
> "Ricardo Aráoz" <ricaraoz at gmail.com> wrote
>> So as not to copy strings many times :
>> while s.isspace() :
>> while s[-1].isspace() :
>> del s[-1]
>> del s
> 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.
sorry, forgot a piece of the code :
s = list(s)
while s.isspace() :
while s[-1].isspace() :
s = ''.join(s)
You only copy the string twice.
More information about the Tutor