See Jamie Zawinksi's famous quote about regular expressions. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.

The actual content of string str (bad name for a variable, by the way, since there's a built-in type of that name) is

"abc INC\","None", "0", "test"

Why not just

str.replace('\\"', '|"')

which will do exactly what you want.

Answer from holdenweb on Stack Overflow
Discussions

how to replace back slash character with empty string in python - Stack Overflow
I want to replace' ... Note that the \ sequence in the string literal in the example becomes an actual backslash followed by a space. When Python scans a string literal and finds an unrecognized escape sequence, it leaves the backslash in the string. (Other programming languages might report an error, or silently remove the backslash.) 2022-08-04T20:45:15.303Z... More on stackoverflow.com
🌐 stackoverflow.com
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
August 21, 2018
string - python replace backslashes to slashes - Stack Overflow
How can I escape the backslashes in the string: 'pictures\12761_1.jpg'? I know about raw string. How can I convert str to raw if I take 'pictures\12761_1.jpg' value from xml file for example? More on stackoverflow.com
🌐 stackoverflow.com
python - python3 replacing double backslash with single backslash - Stack Overflow
Does your_text.replace('\\', '') work? You don't actually have any double literal backslashes there... ... Right, this works. As soon as I put '\' as second argument, it doesn't work anymore. ... I'm going to guess that you don't really need to do this. Often, people print out values and see the double-backslash, but that's just Python's way of unambigiously showing you that there is a single backslash in the string... More on stackoverflow.com
🌐 stackoverflow.com
June 5, 2018
🌐
McNeel Forum
discourse.mcneel.com › scripting
Python - replace backslash in string - rs.documentpath() - Scripting - McNeel Forum
June 16, 2015 - Trying to replace the backslash character in a string obtained with the rs.documentpath() method. The string replace function will not work since the backslash is an escape character. Any way to change my string into a r…
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

🌐
Tutorial Gateway
tutorialgateway.org › python-string-replace
Python String Replace
March 25, 2025 - This program allows the user to enter the text, words to change, and the new text to substitute. Next, we used this Python string replace function to alter the old with the new. We are using the string replace function to change Backslash with ...
Find elsewhere
🌐
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
But yes, three days but only working for about 3 hours each day. ... 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
🌐
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
If you forget to use a raw string, Python may interpret backslashes as escape characters, leading to double backslashes when printed. For example: # Non-raw string with Windows path (accidental escaping) path = "C:\Users\John" # Risky! \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)
Top answer
1 of 2
3

The difference between a string literal and a raw string is the way they are interpreted to create a string object from your source code. The objects they create are not distinct in any way. So there is no such thing as converting a string to a raw string.

In this case, '\018' stands for '\x01', which is the Start-of-Header character, followed by the character '8'.

chr(1) + '8' == '\x018' # True

And as you can see, your string contains no '\\' character.

'\\' in 'бекслеш \018 на точку' # False
2 of 2
2

I think you actually want to replace the control character:

Code

print(s.replace("\x01", ".01"))
# бекслеш .018 на точку

Details

It is clear that the programming language interprets the backslash as a control character.

Actually the control character includes the escape character (\) and the adjacent code (01). Let's see how Python looks at each character:

print(list(s))
# ['б', 'е', 'к', 'с', 'л', 'е', 'ш', ' ', '\x01', '8', ' ', 'н', 'а', ' ', 'т', 'о', 'ч', 'к', 'у']

Notice \x01 is one character, not the backslash alone. You have to replace this entire character.


Addendum

Therefore, a general approach can be to iterate each character and substitute any that belong to the control character category with a new string. This new string should be formatted to mirror the value of the character it replaces. Otherwise, return a normal character.

from unicodedata import category


"".join(".{:02d}".format(ord(char)) if category(char).startswith("C") else char for char in s)
# 'бекслеш .018 на точку'
  • See also a list of unicode categories and this related post.
  • See also this post on removing control characters.
🌐
CodeSpeedy
codespeedy.com › home › replace spaces with backslashes in python
Replace spaces with backslashes in Python - CodeSpeedy
March 23, 2023 - We use the replace() method on the Python string to replace all spaces with backslashes, and it returns a copy of the replaced string. The first argument is the value we want to be replaced, and the second argument is the value that will replace ...
🌐
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-replace-backslashes-to-slashes
Python: Replace Backslashes with Slashes – How to Escape Backslashes and Convert XML Strings to Raw Strings
Use str.replace("\\", "/") to convert backslashes to forward slashes. Raw strings (r"...") simplify working with literal backslashes. Escape backslashes with \\ in normal strings to avoid syntax errors.
🌐
Reddit
reddit.com › r/learnpython › can't replace "\" with str.replace()
r/learnpython on Reddit: Can't replace "\" with str.replace()
January 3, 2025 -

I've tried str.replace("\\", "\") (reddit seems to reed 4 slashes as 2... Assume it's double the amount here) and str.replace(r"\", r""), it doesn't work.

Please help I'm desperate.

json_output = json.load(open(filepath))["subsection"][3]["intro"]

latex_output = ""

for paragraph in json_output:

latex_output += f"{paragraph}"

latex_output = ( latex_output.replace(r"\href", r"\href") .replace(r"\begin", r"\begin") .replace(r"\end", r"\end") .replace(r"\item", r"\item") )

print(latex_output)