[Tutor] wierd replace problem

Alan Gauld alan.gauld at btinternet.com
Mon Sep 13 19:28:46 CEST 2010

"Roelof Wobben" <rwobben at hotmail.com> wrote

> 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.

OK,. Thats replacing a double slash in the data

> for line in file:
>    line2 = line.replace ("\\","")

And this is doing the same. Any double slashes in your file content
will be replaced.

> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items

Now we have an issue of representing characters.

> [('"\'tis', 1),

This is a representation issue. Python is using the \ to escape
the single quote since you are using single quotes on the outside.
Without the backslash the \' would look like the end of the
string to Python.

If you print the actual string it will not show the quote:

for item in letter_items:
    print item[0]

Backslashes are awkward characters because they are used
for several different special purposes as well as being characters
in their own right. If you had tried replacing almost any other
character you would not have gotten confused.


Alan Gauld
Author of the Learn to Program web site

> Why does the \ stays here. It should have gone as the test in the 
> python prompt says.
> Roelof
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list