[Tutor] wierd replace problem
Michael Powe
michael at trollope.org
Mon Sep 13 18:17:47 CEST 2010
On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
>
> Hello,
>
> I have this string called test with the contents of 'het is een wonder \\TIS'
>
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS'
> So that's right.
>
> Now I try the same in a IDE with this programm :
>
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items
>
> But now Im gettting this output :
>
> [('"\'tis', 1),
>
> Why does the \ stays here. It should have gone as the test in the python prompt says.
Hello,
Actually, on closer look I can see the answer.
The original text must look something like this:
\\"'tis the season to be jolly," said santa.
When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1). The appearance of the backslash is
fortuitous. It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string. IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.
Thanks.
mp
--
Michael Powe michael at trollope.org Naugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/6d99cdae/attachment.pgp>
More information about the Tutor
mailing list