python replace single backslash with double backslash

Josh Wood picture Josh Wood · Jun 26, 2013 · Viewed 106.7k times · Source

In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:

directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")

However, this gives an error message saying it doesn't like the double backslash. Can anyone help?

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Jun 26, 2013

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:\Users\Josh\Desktop\20130216"
           ^
           |
       notice the 'r'

Below is the repr version of the above string, that's why you're seeing \\ here. But, in fact the actual string contains just '\' not \\.

>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'

>>> s = r"f\o"
>>> s            #repr representation
'f\\o'
>>> len(s)   #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\' in the output.

>>> print strs
C:\Users\Josh\Desktop\20130216

If you want the string to show '\\' during print then use str.replace:

>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216

repr version will now show \\\\:

>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'