[Tutor] FW: wierd replace problem
Francesco Loffredo
fal at libero.it
Tue Sep 14 17:45:35 CEST 2010
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
Francesco
-------------- next part --------------
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 - Data di rilascio: 09/13/10 08:35:00
More information about the Tutor
mailing list