[Tutor] Using string.strip()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 7 Aug 2001 23:58:22 -0700 (PDT)


On Tue, 7 Aug 2001, Sheila King wrote:

> I have a file that contains something like this:
> 
> N
> ;;
> no, cs student
> ;;
> N
> ;;
> no
> ;;
> S
> ;;
> case-sensitive
> ;;
> Y
> ;;
> yes
> ;;
> N
> ;;
> no
> ;;
> 
> I read it in as a string, let's call it messagebody
>
> Then I do this:
> 
> responses = messagebody.split(';;')
> 
> Now, that will leave leading and trailing '\n' characters on the items
> in the responses list, so I try this:
> 
> for item in responses:
>     item = item.strip()


Ah!  Try this:

###
for i in range(len(responses)):
    responses[i] = responses[i].strip()
###


What you were doing before WAS doing some strip()ping, but unfortunately,
the changes weren't being made to the list elements themselves.  We can
see this if we try this:

###
for i in range(len(responses)):
    item = responses[i]
    item = item.strip()
    ## By this point, item really is strip()ped down, but we haven't
    ## modified responses[i]!
    print repr(item)
    print repr(responses[i])
###


Alternatively, try list comprehensions:

###
responses = [item.strip() for item in responses]
###


Hope this helps!