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
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'
๐ŸŒ
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!

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to deal with windows double backslash in path?
r/learnpython on Reddit: How to deal with Windows double backslash in path?
April 10, 2017 -

I made an automated filemanager with Python. The original target was for Linux. Today, when I tried to use in Windows the path become like this, "C:/Users/reddit_lonely/Dropbox/reddit_lonely/reddit_lonely-pending-note-test\\test\\folder".

I have been looking through solutions over the internet.

  • https://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/.

  • http://stackoverflow.com/questions/11924706/how-to-get-rid-of-double-backslash-in-python-windows-file-path-string

But nothing solve my problem. I see that the main culprit is when path.join() just directly concatenate both path with \ and / together without checking the legality of path.

I think I could make this work by delving around my codes for couple of days. And code path checking manually based on operating system. However, I would like to know if there are more straightforward ways that I could have missed.

SOLVED! The problem was because long file name. Although after I cross checked back in my Linux machine everything works fine.

๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ how-to-get-rid-of-double-backslash-in-python-windows-file-path-string.html
How to get rid of double backslash in python windows file path string?
Description: To eliminate double backslashes from a Windows file path string in Python, you can use the replace() method to replace occurrences of double backslashes with single backslashes.
๐ŸŒ
pytz
pythonhosted.org โ€บ files โ€บ path.html
files.Path โ€“ Path manipulation โ€” files v1.0 documentation
path should be a string, list, tuple, or Path object. Most likely, it will be a string, which creates a new Path object that represents that path. An example would be Path("/usr/bin"). ... Normalizes case, if necessary. Symbolic links are not, however, removed from the path.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 65049867 โ€บ remove-double-backslash-from-a-list-in-python
remove double backslash from a list in python - Stack Overflow
import os import shutil sorc = r'D:\Try\Sorc' dest = r'D:\Try\Dest' #variables for sorc folder_in_sorc = [] files_in_sorc = [] #variables for dest folder_in_dest = [] files_in_dest = [] for root_sorc, dirs_sorc, files_sorc in os.walk(sorc): for folder in dirs_sorc: folder_in_sorc.append(os.path.join(os.path.abspath(root_sorc), folder)) for root_dest, dirs_dest, files_dest in os.walk(dest): for folder in dirs_dest: files_in_dest.append(os.path.join(root_dest, folder)) print(folder_in_sorc) ... It just appears as a double-backslash because that's what repr does. It makes a copy-pastable string that you can put back into your python program.
๐ŸŒ
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 ...
Find elsewhere
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ python
Double backslash in filepaths ? - Post.Byes
April 14, 2007 - '\d' is not a valid escape sequence, so the backslash there survives intact. repr() normalises the string on output, so the (single!) backslash in '\d' is displayed, as always in the repr of strings, as '\\'. > You should either use this: > 'D:\\data_to_te st\\test_global .pd' > > Or this: > r'D:\data_to_te st\test_global. pd' > See also: > ... Contents: General Python FAQ- General Information- What is Python?, What is the Python Software Foundation?, Are there copyright restrictions on the use of Python?, Why was Python created in the fi...
๐ŸŒ
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
\U is a Unicode escape (causes error in Python 3) # To avoid errors, you must escape backslashes: path = "C:\\Users\\John" # Now Python stores it as "C:\Users\John" (single backslashes) print(path) # Output: C:\Users\John (appears correct, but let's check the actual string) print(repr(path)) # Output: 'C:\\Users\\John' (Python represents it with double backslashes) When reading strings from files, JSON, or external sources, backslashes are often escaped twice.
๐ŸŒ
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...
๐ŸŒ
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 some directory in the path starts with a number, os.path.normpath WILL mangle the path by inserting a '\x{hex value}' instead of the desired behavior, '\\{dirname}'. Then you have to go back and clean up and add in the extra backslash in the string before using it. ... str(x) '\\a\\b\\c\\d\\e' The doubled backslashes are a convention for Python string literals. They are NOT actually part of the string. normpath will give you exactly what you really want. The problem comes from the grief you (and Python) go through when interpreting string literals for evaluation into the desired internal string.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-remove-backslash-from-string
Remove Backslashes or Forward slashes from String in Python | bobbyhadz
April 10, 2024 - Copied!string = '/bobby/hadz/com/' print(string) # ๐Ÿ‘‰๏ธ /bobby/hadz/com/ # โœ… Remove leading and trailing forward slash from string new_string = string.strip('/') print(new_string) # ๐Ÿ‘‰๏ธ bobby/hadz/com # ------------------------------------------------------- # โœ… Remove leading and trailing backslash from string string = '\\bobby\\hadz\\com\\' print(string) # ๐Ÿ‘‰๏ธ \bobby\hadz\com\ new_string = string.strip('\\') print(new_string) # ๐Ÿ‘‰๏ธ bobby\hadz\com
๐ŸŒ
Google Groups
groups.google.com โ€บ d โ€บ topic โ€บ comp.lang.python โ€บ YqFaLTzQqRg
Doubled backslashes in Windows paths
October 7, 2016 - But if quotes are present in user-input that represents a file-name, then they might need to be removed. -- Bartc ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... On Fri, Oct 28, 2016 at 8:04 PM, Gilmeh Serda <gilmeh...@nothing.here.invalid> wrote: > > You can use forward slash to avoid the messy problem. There are cases in which you need to use backslash, such as extended paths and command lines. Python 3's pathlib automatically normalizes a Windows path to use backslash.
๐ŸŒ
Tech-Artists.Org
tech-artists.org โ€บ coding
Replacing double slash with single backslash - Coding - Tech-Artists.Org
September 17, 2012 - I recently encountered something for the first time in python, if I execute the following usrPath=os.environ['USERPROFILE'] in Maya script editor or Eyeon Fusion Console it returns path with single backslash but if i exewcute this code in directly in python interpreter i get double slashes โ€ฆ