[Tutor] FW: wierd replace problem

Roelof Wobben rwobben at hotmail.com
Tue Sep 14 18:35:54 CEST 2010

Date: Tue, 14 Sep 2010 17:45:35 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] FW: wierd replace problem

On 14/09/2010 16.29, Roelof Wobben wrote:
> Oke,
> I see the problem.
> When I have this sentence : `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
> 'tis love, 'tis love, that makes the world go round!"'
> And I do string.strip() the output will be :
> `'This and that one does not fit your explanation.
> So I have to strip everything before I strip it.

After some trial and error with the interpreter, I found this:

st = """`'Tis so,' said the Duchess: `and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'""" # notice the
starting and ending triple quotes, just to avoid all the backslashes and
the ambiguities with quoting characters ;-)

wordlist = [thisone.strip("""'",!` :-""") for thisone in st.replace('"',
" ").replace("-"," ").split()]

I don't know if you read the chapter regarding "list comprehensions" in
your tutorial, but this is one of those. First of all, I replace all
double quotes " and dashes - with spaces:
st.replace('"', " ").replace("-"," ")
then I use split() to divide the long string in a list of almost-words.
At the end, with the for clause in the list comprehension, I strip all
leading and trailing non-letters (again, I enclose them in a
triple-quoted string) from each of the elements of the list.

In the end, I have wordlist:

['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of',
'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes',
'the', 'world', 'go', 'round', '']

What about this? Was it confusing?
> Roelof
hello Franceso,
It was not confusing when I read your explanation.
Still im grazy wht with you and Joel the strip works and with me I get errors.
But how can I use the triple quotes when reading a textf-file ?

Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:

More information about the Tutor mailing list