Python替代添加了额外的反斜杠字符

时间:2022-09-13 16:28:07

I have a json string enclosed in single quotes. Hence i am escaping single quotes inside string with a single backslash.

我有一个用单引号括起来的json字符串。因此,我使用单个反斜杠转义字符串中的单引号。

When i write the output to a file, it writes two backslashes in the place of one.

当我将输出写入文件时,它会在一个地方写入两个反斜杠。

A simplified example looks like,

一个简化的例子看起来像,

import re
re.sub(r"'", r"\'", "abcd\'")

It writes to the file,

它写入文件,

abcd\\'

But i prefer it to write,

但我更喜欢写,

abcd\'

1 个解决方案

#1


1  

Your code should work perfectly well:

你的代码应该运行得很好:

>py -3
>>> import re
>>> with open("test.txt", "w") as file:
...     file.write(re.sub(r"'", r"\'", "abcd\'"))
...
6

>cat test.txt
abcd\'

When Python displays a string with a backslash, it will display it as an escaped string - this doesn't mean the extra backslash exists, it's just there to differentiate between an escape character and a real backslash.

当Python显示带有反斜杠的字符串时,它会将其显示为转义字符串 - 这并不意味着存在额外的反斜杠,它只是用来区分转义字符和真正的反斜杠。

>>> r"abcd\'"
"abcd\\'"
>>> print(r"abcd\'")
abcd\'

#1


1  

Your code should work perfectly well:

你的代码应该运行得很好:

>py -3
>>> import re
>>> with open("test.txt", "w") as file:
...     file.write(re.sub(r"'", r"\'", "abcd\'"))
...
6

>cat test.txt
abcd\'

When Python displays a string with a backslash, it will display it as an escaped string - this doesn't mean the extra backslash exists, it's just there to differentiate between an escape character and a real backslash.

当Python显示带有反斜杠的字符串时,它会将其显示为转义字符串 - 这并不意味着存在额外的反斜杠,它只是用来区分转义字符和真正的反斜杠。

>>> r"abcd\'"
"abcd\\'"
>>> print(r"abcd\'")
abcd\'