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'
Answer from Ashwini Chaudhary on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_strings_escape.asp
Python - Escape Characters
An escape character is a backslash \ followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
Discussions

Can't get rid of double backslashes in filepaths -
Isolate the error my friend. In your terminal in the same directory use the os library to verify that the file exists. Use os.path to create the file path do not give it the full path and there should be a method to check if it exists. More on reddit.com
๐ŸŒ r/learnpython
10
3
January 3, 2022
Backslash error
Iโ€™m having some issues with backslashes in my scripts and in python in general. I am using the latest version of python. I downloaded python to an external drive because I lack some storage space. Using command prompt D:\python-lang>python.exe pip install numpy python.exe: can't open file ... More on discuss.python.org
๐ŸŒ discuss.python.org
3
0
November 4, 2023
python - Why do backslashes appear twice? - Stack Overflow
When Python returns the representation ... of an escape sequence), and that's what you're seeing. However, the string itself contains only single backslashes. More information about Python's string literals can be found at: String and Bytes literals in the Python documentation. ... Sign up to request clarification or add additional context in comments. ... I've tried to keep this answer focussed specifically on the "double backslash" ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python regex to replace double backslash with single backslash - Stack Overflow
The print statement removes the double backslash, not the replace. In fact, just doing print original_string => 'class=\"highlight', as well as print new_string => 'class=\"highlight'. You can also confirm this with new_string == original_string => True 2013-05-21T16:11:26.797Z+00:00 ... @mill Wouldn't you still need the backslash to be escaped ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can't get rid of double backslashes in filepaths -
r/learnpython on Reddit: Can't get rid of double backslashes in filepaths -
January 3, 2022 -

I'm concatenating a filepath to open an image with plt.imshow() as follows:

from pathlib import Path
import numpy as np 
import pandas as pd
from scipy.io import loadmat
import pprint
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os

folder = Path('D:\ ... \emotic') 
    #Note that \ ... \ stands for my filepath
original_database = Path(annotations_dict['train']['original_database'][0][50][0][0][0][0])
filename = Path(annotations_dict['train']['filename'][0][50][0])

image_path = os.path.join(folder, original_database, 'images', filename)

img = mpimg.imread(image_path)
imgplot = plt.imshow(img)
plt.show()

print(image_path)
print(repr(image_path))

But I consistently get the following error message: UnidentifiedImageError*: cannot identify image file 'D:\\ ... \\ ... \\ ... \\ ... \\ ... \\emotic\\framesdb\\images\\frame_aztc78d4kjclxv9e.jpg'*

So obviously it can't read the filepath because all the backslashes are doubled. I've found many posts online explaining why this happens (\ is an escape character), but none explaining how to solve this. How do I enforce that the filepath passed on to the plt.imshow() function contains only single backslashes? I've tried solving this issue using the following methods:

  • os.path.normpath( ... ) ==> does nothing;

  • image_path.replace('\\', '\') ==> also does nothing;

  • using r'...' to enforce a raw string with single backslashes ==> still does nothing.

Note also that print(image_path) gives the filepath with single backslashes, while print(repr(image_path)) gives the filepath with double backslashes. And I kinda get the difference and why this is (kinda). But I don't know how to pass on the one with the single backslashes to plt.imshow(), and every method I try ends up giving me the same "double slash" error.

Any help would be greatly appreciated :D

EDIT 1 : The filepath named in the error message is correct. If I take that filepath and replace all the double slashes by single slashes, then put this into my file explorer, the correct image comes up.

EDIT 2 [SOLVED] : Turns out the error wasn't due to single vs. double backslashes in the filepath, but rather to a problem with the matplotlib.image.imread() function that for some reason can't access my image database and triggers the error. If I use an image reader from the PIL library instead, everything works fine:

Solved using this:

from PIL import Image
plt.imshow(Image.open(image_path))

instead of this:

plt.imshow(mpimg.imread(image_path))

Thanks to everyone for helping me isolate the issue!

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Backslash error - Python Help - Discussions on Python.org
November 4, 2023 - Iโ€™m having some issues with backslashes in my scripts and in python in general. I am using the latest version of python. I downloaded python to an external drive because I lack some storage space. Using command prompt D:\python-lang>python.exe pip install numpy python.exe: can't open file ...
๐ŸŒ
Quora
quora.com โ€บ How-do-you-change-a-double-backslash-to-a-single-back-slash-in-Python
How to change a double backslash to a single back slash in Python - Quora
Answer: This is an interesting one. A few important notes before my answer code: * To put a backslash in a string literal, type two backslashes. The first one indicates the start of an escape sequence; the second one indicates you want the escape sequence to produce a backslash. (If you wanted ...
๐ŸŒ
py4u
py4u.org โ€บ blog โ€บ python-regex-to-replace-double-backslash-with-single-backslash
How to Replace Double Backslash with Single Backslash in Python Using Regex: Fixing Common Escape Errors
A JSON file might store a path as "C:\\\\Users\\\\John" (two backslashes escaped to four in JSON). When loaded into Python with json.loads(), this becomes "C:\\Users\\John" (double backslashes).
Find elsewhere
Top answer
1 of 2
127

What you are seeing is the representation of my_string created by its __repr__() method. If you print it, you can see that you've actually got single backslashes, just as you intended:

>>> print(my_string)
why\does\it\happen?

The string below has three characters in it, not four:

>>> 'a\\b'
'a\\b'
>>> len('a\\b')
3

You can get the standard representation of a string (or any other object) with the repr() built-in function:

>>> print(repr(my_string))
'why\\does\\it\\happen?'

Python represents backslashes in strings as \\ because the backslash is an escape character - for instance, \n represents a newline, and \t represents a tab.

This can sometimes get you into trouble:

>>> print("this\text\is\not\what\it\seems")
this    ext\is
ot\what\it\seems

Because of this, there needs to be a way to tell Python you really want the two characters \n rather than a newline, and you do that by escaping the backslash itself, with another one:

>>> print("this\\text\is\what\you\\need")
this\text\is\what\you\need

When Python returns the representation of a string, it plays safe, escaping all backslashes (even if they wouldn't otherwise be part of an escape sequence), and that's what you're seeing. However, the string itself contains only single backslashes.

More information about Python's string literals can be found at: String and Bytes literals in the Python documentation.

2 of 2
15

As Zero Piraeus's answer explains, using single backslashes like this (outside of raw string literals) is a bad idea.

But there's an additional problem: in the future, it will be an error to use an undefined escape sequence like \d, instead of meaning a literal backslash followed by a d. So, instead of just getting lucky that your string happened to use \d instead of \t so it did what you probably wanted, it will definitely not do what you want.

As of 3.6, it causes a DeprecationWarning, although most people don't see those. As of 3.12, it causes a SyntaxWarning. This will become a SyntaxError in some future version, per the docs on escape sequences.

$ python3.6 -Wall -c 'print("\d")'
<string>:1: DeprecationWarning: invalid escape sequence \d
\d
$ python3.12 -c 'print("\d")'
<string>:1: SyntaxWarning: invalid escape sequence '\d'
\d

In many other languages, including C, using a backslash that doesn't start an escape sequence means the backslash is ignored.

In a few languages, including Python, a backslash that doesn't start an escape sequence is a literal backslash.

In some languages, to avoid confusion about whether the language is C-like or Python-like, and to avoid the problem with \Foo working but \foo not working, a backslash that doesn't start an escape sequence is illegal.

๐ŸŒ
Pychallenger
pychallenger.com โ€บ blog โ€บ tutorials โ€บ intermediate-python โ€บ strings-ii โ€บ tutorial-escape-characters-python
Escape Characters | Pychallenger
For example: ... Another commonly used escape character is the newline character \n. As the name suggests, it inserts a new line within the string. For example: ... Since the backslash is reserved for escape characters in Python, you need to escape it by using a double backslash \\:
๐ŸŒ
MojoAuth
mojoauth.com โ€บ escaping โ€บ python-string-escaping-in-python
Python String Escaping in Python | Escaping Methods in Programming Languages
Implementing string escaping in Python is straightforward. Use the backslash to precede any special character that needs to be included in the string. Here's a basic example demonstrating how to use string escaping effectively: # Example of ...
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-2466.html
Replace Single Backslash with Double Backslash in python
March 19, 2017 - I have a need to replace single backslashes with double backslashes. I know that the replace method of the string object can be used, however I'm not able to figure out the correct combination given that the backslash serves as an escape character. A...
๐ŸŒ
Quora
quora.com โ€บ How-do-you-backslash-a-string-in-Python
How to backslash a string in Python - Quora
To include literal backslashes in Python strings you must escape each backslash (write \) or use raw string literals when appropriate. Details and examples: ... Single backslash: use a doubled backslash in the string literal: "\" -> produces a one-character string containing .
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 5550bce776b8fe9acf000289
NEED HELP DONT KNOW HOW TO GET AN ESCAPE BACKSLASH | Codecademy
There is nothing special to make a backslash an escape backslash other than typing it directly in front of a quote mark that is within a string. I am new to Python as you are and this is just how I see it.
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ string-manipulation-for-python-coders โ€บ lessons โ€บ unleashing-python-strings-a-beginners-guide-to-escaping-and-special-characters
A Beginner's Guide to Escaping and Special Characters
print("This is a string\nThis is on a new line") # Prints a new line after "This is a string" print("Here is a\ttab space") # Prints "Here is a tab space" print("This is a backslash \\") # Prints "This is a backslash \" ... table = "Name\tAge\nAlice\t23\nBob\t25" print(table) # Outputs data like a table """ Name Age Alice 23 Bob 25 """ ... single_quoted = 'This is a "quoted" word' # using single quotes to print double quotes inside the string print(single_quoted) # This is a "quoted" word double_quoted = "This is a 'quoted' word" # using double quotes to print single quotes inside the string print(double_quoted) # This is a 'quoted' word ... Python strings can store any character, thereby enabling the use of any alphabet, symbols, or emojis:
๐ŸŒ
TOOLSQA
toolsqa.com โ€บ python โ€บ escape-sequences-in-python
Escape Sequences in Python (with examples) - ToolsQA
The escape character gives a new behavior to the character, i.e., a double quote (") next to it. In other words, we have used the double quote and backslash in combination (\"). That combination is one of the escape sequences in Python.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-escape-characters
Python Escape Characters - GeeksforGeeks
April 28, 2025 - ... The \\ escape character inserts a literal backslash in the string. ... The \' escape character allows you to insert a single quote within a string that is enclosed by single quotes. ... It's a great day! The \" escape character allows you ...
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ str โ€บ escapes.html
Escape Characters โ€” Python Reference (The Right Way) 0.1 documentation
For example, the string literal rโ€nโ€ consists of two characters: a backslash and a lowercase โ€˜nโ€™. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, rโ€โ€œโ€ is a valid string literal consisting of two characters: a backslash and a double ...
Top answer
1 of 5
31

The double backslash is not wrong, python represents it way that to the user. In each double backslash \\, the first one escapes the second to imply an actual backslash. If a = r'raw s\tring' and b = 'raw s\\tring' (no 'r' and explicit double slash) then they are both represented as 'raw s\\tring'.

>>> a = r'raw s\tring'
>>> b = 'raw s\\tring'
>>> a
'raw s\\tring'
>>> b
'raw s\\tring'

For clarification, when you print the string, you'd see it as it would get used, like in a path - with just one backslash:

>>> print(a)
raw s\tring
>>> print(b)
raw s\tring

And in this printed string case, the \t doesn't imply a tab, it's a backslash \ followed by the letter 't'.

Otherwise, a string with no 'r' prefix and a single backslash would escape the character after it, making it evaluate the 't' following it == tab:

>>> t = 'not raw s\tring'  # here '\t' = tab
>>> t
'not raw s\tring'
>>> print(t)  # will print a tab (and no letter 't' in 's\tring')
not raw s       ring

So in the PDF path+name:

>>> item = 'xyz'
>>> PDF = r'C:\Users\user\Desktop\File_%s.pdf' % item
>>> PDF         # the representation of the string, also in error messages
'C:\\Users\\user\\Desktop\\File_xyz.pdf'
>>> print(PDF)  # "as used"
C:\Users\user\Desktop\File_xyz.pdf

More info about escape sequences in the table here. Also see __str__ vs __repr__.

2 of 5
12

Double backslashes are due to r, raw string:

r'C:\Users\user\Desktop\File_%s.pdf' ,

It is used because the \ might escape some of the characters.

>>> strs = "c:\desktop\notebook"

>>> print strs                #here print thinks that \n in \notebook is the newline char
c:\desktop
otebook

>>> strs = r"c:\desktop\notebook"  #using r'' escapes the \
>>> print strs

c:\desktop\notebook

>>> print repr(strs)   #actual content of strs
'c:\\desktop\\notebook'
๐ŸŒ
Compile7
compile7.org โ€บ escaping โ€บ how-to-use-python-string-escaping-in-python
How to use Python String Escaping in Python | Escaping Methods in Programming Languages
This is done by preceding the literal quote character with a backslash (\). For example, to include double quotes within a double-quoted string, you'd use \". ... Without escaping, Python will interpret the inner quote as the end of the string, ...