why not use string.replace()?
>>> s = 'some \\\\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Or with "raw" strings:
>>> s = r'some \\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Since the escape character is complicated, you still need to escape it so it does not escape the '
why not use string.replace()?
>>> s = 'some \\\\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Or with "raw" strings:
>>> s = r'some \\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Since the escape character is complicated, you still need to escape it so it does not escape the '
Just use .replace() twice!
I had the following path: C:\\Users\\XXXXX\\Desktop\\PMI APP GIT\\pmi-app\\niton x5 test data
To convert \ to single backslashes, i just did the following:
path_to_file = path_to_file.replace('\\','*')
path_to_file = path_to_file.replace('**', '\\')
first operation creates ** for every \ and second operation escapes the first slash, replacing ** with a single \.
Result:
C:**Users**z0044wmy**Desktop**PMI APP GIT**pmi-app**GENERATED_REPORTS
C:\Users\z0044wmy\Desktop\PMI APP GIT\pmi-app\GENERATED_REPORTS
Replacing double slash with single backslash
Python - replace backslash in string - rs.documentpath()
Backslash error
How to replace double back slashes returned by AppContext.BaseDirectory in C#
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!
The character‘\’is a special character.
https://learn.microsoft.com/en-us/cpp/c-language/escape-sequences?view=msvc-170
During debugging, it is displayed as “C:\\Users\\BGates\\Databases\\ProductionDatabase\\Company.db”, but the actual content is “C:\Users\BGates\Databases\ProductionDatabase\Company.db”.
When looking at the contents of a string during debugging, it is good to use the Text Visualizer.
Hi @Tom Meier , Welcome to Microsoft Q&A,
To replace double backslashes with single backslashes, you can use the Replace method. The problem you are encountering may be because the backslash in the string is an escape character, so you need to be careful when replacing it. The following is a correct code example:
string fileName = "Company.db";
string path = Path.Combine(Global.Directory, fileName).Replace("\\\\", "\\");
In this example, Replace("\\\\", "\\") will replace all double backslashes with single backslashes. Note that in C#, the backslash is an escape character, so you need to use two backslashes to represent an actual backslash.
Alternatively, you can use a verbatim string to avoid the escape character issue, as shown below:
string fileName = "Company.db";
string path = Path.Combine(Global.Directory, fileName).Replace(@"\\", @"\");
This will ensure that all double backslashes in the path are replaced with single backslashes.
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
I have been searching for several explanations online but I am not finding a detailed, intuitive understanding as to why we need double backslashes in regex expressions. They say things like "escape the escape character" but that is where I get lost.
If I am coding in R and have a dataset of planets (random example) where I want to literally find a row with a string value "planet.name," would we use ^planet\.name$ or ^planet\\.name$ ?
From my understanding, it seems to be the former since all we want is to find a literal string that starts with "planet" followed by a period "." followed by, and ended with, "name," and it seems this description translates exactly into the pattern specified by the former. I feel like someone may answer my question by saying, "well, the backslash has a special meaning and has to be escaped itself, thus we use two backslashes" -- that is the sentence I don't understand; my thoughts are "I mean, I know the backslash has a special meaning... it is to escape the special meaning of the following character (in this case, the period) to be the character literal to be searched for... and great!" Maybe I do not have the full dots to begin with and therefore am not able to connect them based on what I have read, so could anyone please explain in detail why we actually use two backslashes to do that job? Thank you so much!!
The goal: 'apple' -> 'app\e'
This doesn't work:
>>> "apple".replace('l', '\\')
'app\\e'This also doesn't work:
>>> "apple".replace('l', '\')
File "<stdin>", line 1
"apple".replace('l', '\')
^
SyntaxError: EOL while scanning string literal