简体   繁体   English

Python:为什么转义反斜杠会产生 2 个反斜杠?

[英]Python: why does escaping a backslash produce 2 backslashes?

I want to be able to use backslashes in string literals, for example: C:\\file.txt我希望能够在字符串文字中使用反斜杠,例如: C:\\file.txt

I was expecting to be able to escape the backslash with "\\\\" , but for some weird reason that produces two backslashes instead of one.我希望能够用"\\\\"转义反斜杠,但出于某种奇怪的原因,它会产生两个反斜杠而不是一个。 Why?为什么?

MVCE: MVCE:

with open("temp.csv", 'w', encoding='utf-8') as f:
    d = { "filepath" : "C:\\bahä.txt" }
    s = json.dumps(d, ensure_ascii=False)
    f.write(s)

Expected behavior: file content should be C:\\bahä.txt预期行为:文件内容应为C:\\bahä.txt

Actual behavior: file content is C:\\\\bahä.txt实际行为:文件内容为C:\\\\bahä.txt

The problem here is that you are serializing to JSON.这里的问题是您正在序列化为 JSON。

In Json some special characters are serialized with a \\ prepended: https://stackoverflow.com/a/19176131/551045在 Json 中,一些特殊字符被序列化并带有\\前缀: https : //stackoverflow.com/a/19176131/551045

So a \\ is always \\\\ in proper serialized JSON data.因此,在正确的序列化 JSON 数据中, \\始终为\\\\

If you change your code to:如果您将代码更改为:

with open("temp.csv", 'w', encoding='utf-8') as f:
    d = "C:\\bah.txt"
    f.write(d)

You'll see that your file will only contain one slash.你会看到你的文件只包含一个斜杠。

BTW that's why we always ask for MVCE even if the problem seems "trivial".顺便说一句,这就是为什么我们总是要求 MVCE,即使问题看起来“微不足道”。

In JSON you need to escape the backslash.在 JSON 中,您需要转义反斜杠。 That is why when you dump your string it keeps the backslash escaped.这就是为什么当您转储字符串时,它会保留反斜杠转义。 if you have only one backslash, eg "C:\\bahä.txt" then \\b is backspace (ie if it wasn't b after the backslash to produce valid escape sequence it would be invalid json).如果您只有一个反斜杠,例如"C:\\bahä.txt"那么\\b是退格"C:\\bahä.txt" (即,如果在反斜杠后面不是b来生成有效的转义序列,那么它将是无效的 json)。 you can test and see that你可以测试看看

import json
with open("temp.json", 'w', encoding='utf-8') as f:
    d = {"filepath":"\ "}
    s = json.dumps(d, ensure_ascii=False)
    f.write(s)

or或者

import json
with open("temp.json", 'w', encoding='utf-8') as f:
    d = { "filepath" : r"\b" }
    s = json.dumps(d, ensure_ascii=False)
    f.write(s)

both will again produce escaped backslash (ie \\\\ ) in the resulting json.两者都会在生成的 json 中再次产生转义的反斜杠(即\\\\ )。

https://stackoverflow.com/a/19176131/4046632 https://stackoverflow.com/a/19176131/4046632

As a side note - you are writing json, use the proper extension - .json , not .csv附带说明 - 您正在编写 json,请使用正确的扩展名 - .json ,而不是.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM