Python3:

>>> b'\\u201c'.decode('unicode_escape')
'โ€œ'

or

>>> '\\u201c'.encode().decode('unicode_escape')
'โ€œ'
Answer from max5555 on Stack Overflow
๐ŸŒ
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 ...
Discussions

string - python replace single backslash with double backslash - Stack Overflow
How can I put an actual backslash in a string literal (not use it for an escape sequence)? (4 answers) Closed 3 years ago. In python, I am trying to replace a single backslash ("\") with a double backslash("\"). More on stackoverflow.com
๐ŸŒ stackoverflow.com
Replacing double slash with single backslash
Itโ€™s returning the same string value in either case; the only difference is in how itโ€™s being printed. Try this directly in a python interpreter / IDLE (after importing os): ยท The explicit print gives you the human-readable representation of your string. More on tech-artists.org
๐ŸŒ tech-artists.org
0
0
September 17, 2012
How to use replace double backslashes to single one for byte string in Python - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I want to replace double backslashes to single one for byte string in Python. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to replace double backslash to single backslash - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. ... Closed 3 years ago. many of the findings are for python2, my case is python3: I need to replace double back slash to single back slash ... An "accepted answer" from this post python3 replacing double backslash with single backslash ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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
Follow these steps to replace double backslashes with single backslashes using Pythonโ€™s re module: The re module provides regex functionality in Python. Import it first: ... Letโ€™s use a string with double backslashes (e.g., from JSON or a file).
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ how-to-replace-a-double-backslash-with-a-single-backslash-in-python.html
How to replace a double backslash with a single backslash in python?
In Python, you can replace double backslashes (\\) with a single backslash (\) using string manipulation methods. Here's how you can do it: # Input string with double backslashes input_string = "C:\\Users\\Username\\Documents" # Replace double backslashes with a single backslash output_string ...
๐ŸŒ
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โ€ฆ
Find elsewhere
๐ŸŒ
Python
python-list.python.narkive.com โ€บ Z4CBbwL7 โ€บ how-to-replace-double-backslash-with-one-backslash-in-string
how to replace double backslash with one backslash in string...
You never had a 3 char string: the \ escapes are valid in python code, but not in strings read from the user by any means. Typing \x20 in a Tkinter entry is the same as reading a file containing the characters '\', 'x', '2' and '0': you get exactly these characters, not the character represented by this string if you had put it in your code. Post by Vincent Texier I've tried a re.sub(r'\\', chr(92)) but chr(92) is a double backslash again.
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ python
how to replace double backslash with one backslash in string... - Post.Byes
November 1, 2015 - > > How can I replace the escape character from the string with the > corresponding char, and get my 3 char string back ?[/color] You never had a 3 char string: the \ escapes are valid in python code, but not in strings read from the user by any means. Typing \x20 in a Tkinter entry is the same as reading a file containing the characters '\', 'x', '2' and '0': you get exactly these characters, not the character represented by this string if you had put it in your code. [color=blue] > I've tried a re.sub(r'\\', chr(92)) but chr(92) is a double backslash > again.[/color] No, it's not: you're confusing how it is represented ('\\') and what it is (a *single* back-slash).
Top answer
1 of 2
9

Take a closer look at the string, they are all single slash.

In [26]: my_str[0]
Out[26]: '\\'

In [27]: my_str[1]
Out[27]: 'x'

In [28]: len(my_str[0])
Out[28]: 1

And my_str.replace('\\','\') won't work because the token here is \', which escapes ' and waits for the another closing '.
Use my_str.replace('\\', '') instead


Update: after few more days, I realize the following discussion may also be helpful. If the intension of a string with escape ('\\x' or '\\u') are eventually hex/unicode literals, they can be decoded by escape_decode.

import codecs
print(len(b'\x32'), b'\x32')                # 1 hex literal, '\x32' == '2'
print(len(b'\\x32'), b'\\x32')              # 4 chars including escapes
print(codecs.escape_decode('\\x32', 'hex')) # chars->literal, 4->1

# 1 b'2'
# 4 b'\\x32'
# (b'2', 4)

s = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z'
ed, _ = codecs.escape_decode(s, 'hex')
print(len(s), s)
print(len(ed), ed)

# 49 \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z
# 22 b'\xa5\xc0\xe6aK\xf9\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z'
2 of 2
1

If you do

s  = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z\\x'

s = s.replace('\\','\')

print(s)

you get

 File "main.py", line 3
    s = s.replace('\\','\')
                         ^
SyntaxError: EOL while scanning string literal

because in '\' the \ escapes the ' . Your string is left open.

You do not have any double \ in s - its just displaying it as such, do distinguish it from \ used to escape stuff if you inspect it.

If you print(s) you get \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z\x

๐ŸŒ
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...
๐ŸŒ
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\ result = string.replace('\\', '\\\\') print(result) # ๐Ÿ‘‰๏ธ \\bobby\\hadz\\com\\ ... We used the str.replace() method to replace a single backslash with two ...
๐ŸŒ
devRant
devrant.com โ€บ rants โ€บ 1204373 โ€บ me-spends-three-days-trying-to-format-a-string-to-replace-two-backslashes-with-o
Me: *spends three days trying to format a string to replace two backslashes with one* Python: Here you go! str = byte - devRant
Hmm not the best way but off the top of my head I would've converted to character array iterated through it and check for the current and next character being a backslash and then only add it once to the new built up string
๐ŸŒ
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!

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 45357106 โ€บ replace-double-backslash-with-single-backslash-in-bytestring
python 3.x - Replace double backslash with single backslash in bytestring - Stack Overflow
July 28, 2017 - import ast def remove_double_backslashes(b): return ast.literal_eval(str(b).replace('\\\\', '\\')) In case you are using an older Python version than 3.2, you would probably need to replace ast.literal_eval with eval. That built-in function can sometimes be dangerous, however I as an amateur programmer can't think why eval(str(b)), where b is a bytes object, could do any harm.