[Tutor] Using string.strip()
Hans Nowak
hnowak@cuci.nl
Wed, 8 Aug 2001 09:15:28 +0200
>===== Original Message From Sheila King <sheila@thinkspot.net> =====
>OK, I'm having another one of my dumb moments...
>
>As I read the docs for the strip() function for strings, it removes all
>leading and trailing characters that are defined in the
>string.whitespace constant, correct? And I even looked in there and SAW
>the '\n' character listed as a whitespace element.
>
>Now, why isn't this working?
>
>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()
Note that this for loop "as is" doesn't do anything to the responses list...
it just strips an item, then discards it. Maybe this is the reason why it
doesn't have the desired effect?
>But when I run it and print out the results, I still have leading and
>trailing '\n' characters on the individual list elements, as though the
>strip() function had no effect.
The following works for me:
import string
responses = messagebody.split(";;")
responses = map(string.strip, responses)
print responses
HTH,
--Hans Nowak