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?
Just use . replace() twice! first operation creates ** for every \ and second operation escapes the first slash, replacing ** with a single \ .
The division result of two numbers can be an integer or a floating-point number. In python version 3+, both the single slash (/) operator and the double slash (//) operator are used to get the division result containing the floating-point value.
The correct way would be s. replace('/', '\\') . Right now when it's running it will just give you \f which is a linefeed character.
To replace all backslashes in a string:Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.
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'
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re s = "C:\Users\Josh\Desktop" print s print re.escape(s)
Output :
C:\Users\Josh\Desktop C:\\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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With