python replace single backslash with double backslash
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 strsC:\Users\Josh\Desktop\20130216
If you want the string to show '\\'
during print
then use str.replace
:
>>> new_strs = strs.replace('\\','\\\\')>>> print new_strsC:\\Users\\Josh\\Desktop\\20130216
repr
version will now show \\\\
:
>>> new_strs'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import res = "C:\Users\Josh\Desktop"print sprint re.escape(s)
Output :
C:\Users\Josh\DesktopC:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.