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__.

Answer from aneroid on Stack Overflow
🌐
Python Forum
python-forum.io › thread-2466.html
Replace Single Backslash with Double Backslash in python
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...
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'
🌐
Reuven Lerner
lerner.co.il › home › blog › python › avoiding windows backslash problems with python’s raw strings
Avoiding Windows backslash problems with Python's raw strings — Reuven Lerner
July 24, 2018 - For example: ... What if you want to print a literal ‘\n’ in your code? That is, you want a backslash, followed by an “n”? Then you’ll need to double the backslash:The “\\” in a string will result in a single backslash character.
🌐
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 …
🌐
Python.org
discuss.python.org › python help
How to handle '\\' as a delimiter in Python strings - Python Help - Discussions on Python.org
August 31, 2023 - I am having to load and handle strings from an external data source that are delimited by double backslash. I need to return the sorted and de-duplicated delimited string e.g. input_string = ‘bananas\\apples\\pears\\apples\\bananas\\pears’ the return string should be: ‘apples\\bananas\\pears’ This works: input_string = 'bananas\\apples\\pears\\apples\\bananas\\pears' distinct_items = set(x.strip() for x in input_string.split('\\')) print('\\'.join(sorted(distinct_items))) but this doe...
🌐
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
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.
Find elsewhere
🌐
Python Pool
pythonpool.com › home › blog › working with python double slash operator
Working With Python Double Slash Operator - Python Pool
January 1, 2024 - “C:\Users\Owner\Documents\ashwini” in python. If we just print like this- print(“C:\Users\Owner\Documents\ashwini”) ... SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape · So, we have to use a double backslash (‘\’) instead of (‘\’).
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.

🌐
YouTube
youtube.com › watch
how to print double backslash in python - YouTube
Download this code from https://codegive.com Certainly! In Python, if you want to print a double backslash (\\), you need to use a double backslash because a...
Published   December 14, 2023
🌐
Python.org
discuss.python.org › python help
Variable has a backslash, when the variable is added to create a list, the backslash is duplicated, how can I avoid it? - Python Help - Discussions on Python.org
June 19, 2023 - Hello All. I am new in python and let me explain what do I need… I have to add some variables to a program using raw_input so I have 3 variables, name_input, value_input and description_input, after type these inputs I create the following code: print (value_input) Name = ['name', name_input ] Value = ['value', value_input] Description = ['description', description_input] print (Value) The problem is when the value_input has a backslash, for example value_input ...
🌐
Narkive
tutor.python.narkive.com › QFC00Bwa › double-backslash-in-windows-paths
[Tutor] double backslash in Windows paths
If you pass it a path, and say ... backslash in the string before using it. ... str(x) '\\a\\b\\c\\d\\e' The doubled backslashes are a convention for Python string literals....
🌐
YouTube
youtube.com › watch
what is double backslash in python - YouTube
Instantly Download or Run the code at https://codegive.com understanding double backslash in pythonin python, the double backslash (\\) is used as an escape...
Published   February 29, 2024
Top answer
1 of 5
117

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"')
baz "\"
2 of 5
57

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.