68

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?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Josh Wood
  • 1,598
  • 3
  • 16
  • 21
  • It's not gonna like the single back slashes either – Ryan Haining Jun 26 '13 at 18:09
  • A backspace is an [escape character](http://docs.python.org/2/reference/lexical_analysis.html#grammar-token-escapeseq). You can't use it by itself. – Santa Jun 26 '13 at 18:09
  • You can get away with using forward slashes too; might be easier for you. – squiguy Jun 26 '13 at 18:11
  • 3
    I don't understand the point of this question. Also why does a basic misunderstanding of escape characters deserve a 50 point bounty? – Tim Seguine Sep 27 '16 at 19:30
  • 3
    just trying to get more/better suggestions, as these don't solve my problem. Figured it's worth a try, to avoid asking a brand new question. – Demis Oct 04 '16 at 18:29
  • See also: [Windows path in Python](https://stackoverflow.com/questions/2953834/windows-path-in-python) – Karl Knechtel Aug 05 '22 at 23:36
  • "However, this gives an error message saying it doesn't like the double backslash." In fact, it is the single backslash that causes a problem here. Where the code says `"\", "\\")`, first Python sees a string literal `"\", "` (the closing quote after the first backslash is *part of the string, not the end*), and then `\` (a line continuation character, and then `\")` (disallowed garbage after the line continuation character). – Karl Knechtel Aug 05 '22 at 23:41
  • (Although in 3.x, `\U` causes a problem too, and `\201` means the wrong thing regardless.) – Karl Knechtel Aug 05 '22 at 23:51

9 Answers9

84

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'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    How do you make sure that an existing '\\' doesn't get doubled? Eg. you want only a maximum of double-backslash (in `print` version)? – Demis Sep 27 '16 at 19:03
  • @Demis Can you give an example? – Ashwini Chaudhary Sep 27 '16 at 20:03
  • 1
    I have a script where I need the stored filepath to contain double-\\'s (to send to a program that requires this escaping), but the input file path sometimes already contains this (provided by user/Python script), and sometimes doesn't (contains only single-\'s). I want to sanitize the input to make sure all \'s are converted to exactly \\. Eg. The user might provide \\'s if they are aware of the program's \\ syntax, but if they don't they will provide single \'s. I *could* require only single-\'s all the time, but thought it mightn't be too hard to sanitize this properly for either case. – Demis Sep 29 '16 at 04:56
  • 4
    @Demis: Have a look at _os.path.normpath(path)_. This removes all duplicate backslashes. Afterwards, replace the single backslash with the double backslash. – Cerno Oct 27 '16 at 11:39
  • prefixing a string with `r` is awesome for pasting pathes into the windows cmd python shell – lucidbrot Jul 30 '19 at 13:32
  • 1
    Thanks Demis and @Cerno. The other answers using 'r' to prefix a string or the re regex library answer the initial question perfectly. But I was looking for how to handle this with user input(). Using os.path.normalpath() was exactly what I needed. – Glenn Wark Apr 27 '23 at 15:50
25

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.

Rewanth Tammana
  • 1,453
  • 17
  • 20
  • Please provide some context and explanation to go with your code. Also check the formatting of your code. – James K Oct 03 '16 at 22:22
  • @JamesK Sorry for the explanation.Let me correct it. – Rewanth Tammana Oct 04 '16 at 09:04
  • 1
    That's great that there's a function to do this for you! This is exactly what I needed, and is much prettier than the quadruple backslashes. Simple and clear indeed. – Demis Oct 04 '16 at 18:35
  • re.escape unfortunately also escapes spaces "\ \ \ " – Kjeld Flarup Apr 05 '18 at 14:19
  • 1
    re.escape also escapes . so print(re.escape('bob.txt') outputs 'bob\.txt' Escape is intended to escape arbitrary strings to be used in regular expressions. It is not intended to escape file paths. – Brian C. May 25 '18 at 17:17
  • in my case, this also escaped `:` which became `\:` resulting in the path not working :-( – lenooh Sep 08 '18 at 19:56
  • This answer is not valid - it escapes not only \ but also many other special charaters. – v2v1 Nov 17 '20 at 03:15
  • In 3.x, `s = "C:\Users\Josh\Desktop"` is already a syntax error, because `\U` starts an 8-hex-digit Unicode escape. (In 2.x, this would only be recognized within a string with a `u` prefix or when using `from __future__ import unicode_literals`.) – Karl Knechtel Aug 05 '22 at 23:50
9

Use escape characters: "full\\path\\here", "\\" and "\\\\"

alexpinho98
  • 909
  • 8
  • 14
3

In python \ (backslash) is used as an escape character. What this means that in places where you wish to insert a special character (such as newline), you would use the backslash and another character (\n for newline)

With your example string you would notice that when you put "C:\Users\Josh\Desktop\20130216" in the repl you will get "C:\\Users\\Josh\\Desktop\x8130216". This is because \2 has a special meaning in a python string. If you wish to specify \ then you need to put two \\ in your string.

"C:\\Users\\Josh\\Desktop\\28130216"

The other option is to notify python that your entire string must NOT use \ as an escape character by pre-pending the string with r

r"C:\Users\Josh\Desktop\20130216"

This is a "raw" string, and very useful in situations where you need to use lots of backslashes such as with regular expression strings.

In case you still wish to replace that single \ with \\ you would then use:

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

Notice that I am not using r' in the last two strings above. This is because, when you use the r' form of strings you cannot end that string with a single \

Why can't Python's raw string literals end with a single backslash?

https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-are-escape-characters/

Community
  • 1
  • 1
RFV
  • 831
  • 8
  • 22
2

Maybe a syntax error in your case, you may change the line to:

directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')

which give you the right following output:

C:\\Users\\Josh\\Desktop\\20130216
A. STEFANI
  • 6,707
  • 1
  • 23
  • 48
2

The backslash indicates a special escape character. Therefore, directory = path_to_directory.replace("\", "\\") would cause Python to think that the first argument to replace didn't end until the starting quotation of the second argument since it understood the ending quotation as an escape character.

directory=path_to_directory.replace("\\","\\\\")
abacles
  • 849
  • 1
  • 7
  • 15
0

Given the source string, manipulation with os.path might make more sense, but here's a string solution;

>>> s=r"C:\Users\Josh\Desktop\\20130216"
>>> '\\\\'.join(filter(bool, s.split('\\')))
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

Note that split treats the \\ in the source string as a delimited empty string. Using filter gets rid of those empty strings so join won't double the already doubled backslashes. Unfortunately, if you have 3 or more, they get reduced to doubled backslashes, but I don't think that hurts you in a windows path expression.

CAB
  • 1,106
  • 9
  • 23
-1

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
AHRG
  • 1
-3

Use:

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

Escape the \ character.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
rocker_raj
  • 159
  • 12