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

Ricardo Aráoz ricaraoz at gmail.com
Tue Oct 2 15:46:33 CEST 2007


Andrew James wrote:
> *headbang*
> 
> I'm an idiot. s=s[:-2] should be s=s[:-1].
> 
> Andrew James wrote:
>> And as soon as I send it again I realise a pretty stupid error. The 
>> two loops shouldn't be nested.
>>
>> Andrew James wrote:
>>> Helps if I send it to the group...
>>>
>>> And Kent, I didn't post it originally because I figured the other guy 
>>> was still working on his script. Besides, I didn't think it'd be that 
>>> far fetched for you to assume I was using something like "while s[0] 
>>> == ' ':"
>>>
>>> Andrew James wrote:
>>>> I'm always nervous about sharing my code... It's like being back in 
>>>> high school, I don't want the other kids to laugh at me. Anyway, 
>>>> running that in IDLE with a string such as '                      
>>>> testing.          ' Will print '                    testing' at the 
>>>> end of the first (second, really) loop.
>>>>
>>>> def strip(s):
>>>>    while s[0].isspace() == True:
>>>>        while s[-1].isspace() == True:
>>>>            s = s[:-2]
>>>>            print s
>>>>        s = s[1:]
>>>>        print s
>>>>
>>>> test = raw_input('Enter a string with plenty of leading and trailing 
>>>> whitespace:')
>>>>
>>>> strip(test)
>>>>
>>>> Alan Gauld wrote:
>>>>> "Andrew James" <aijames at exemail.com.au> wrote
>>>>>
>>>>>  
>>>>>> string containing a single space ' ' but even using s[-1].isspace() I
>>>>>> lose punctuation marks. Any idea why that's happening?
>>>>>>     
>>>>> care to show us what you are doing?
>>>>>
>>>>>  
>>>>>>>> ';'.isspace()
>>>>>>>>         
>>>>> False
>>>>>
>>>>> So puntuation should not show up as true...
>>>>>
>>>>> Alan G.
>>>>>

So as not to copy strings many times :

while s[0].isspace() :
    while s[-1].isspace() :
        del s[-1]
    del s[0]







More information about the Tutor mailing list