如何在 C++ 中将 Python 字符串转换为其转义版本?

How to convert a Python string into its escaped version in C++?

我正在尝试编写一个 Python 程序,该程序读取文件并将内容打印为单个字符串,因为它将以 C++ 格式转义。这是因为字符串将从 Python 输出中复制并粘贴到 C++ 程序中(C++ 字符串变量定义)。

基本上我要转换

<!DOCTYPE html>
<html>
<style>
.card{
    max-width: 400px;
     min-height: 250px;
     background: #02b875;
     padding: 30px;
     box-sizing: border-box;
     color: #FFF;
     margin:20px;
     box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);
}
</style>

<body>
<div class="card">
  <h4>The ESP32 Update web page without refresh</h4><br>
  <h1>Sensor Value:<span id="ADCValue">0</span></h1><br>
</div>
</body>

<script>
setInterval(function() {
  // Call a function repetatively with 0.1 Second interval
  getData();
}, 100); //100mSeconds update rate

function getData() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("ADCValue").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "readADC", true);
  xhttp.send();
}
</script>
</html>

至此

<!DOCTYPE html>\n<html>\n<style>\n.card{\n    max-width: 400px;\n     min-height: 250px;\n     background: #02b875;\n     padding: 30px;\n     box-sizing: border-box;\n     color: #FFF;\n     margin:20px;\n     box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);\n}\n</style>\n\n<body>\n<div class=\"card\">\n  <h4>The ESP32 Update web page without refresh</h4><br>\n  <h1>Sensor Value:<span id=\"ADCValue\">0</span></h1><br>\n</div>\n</body>\n\n<script>\nsetInterval(function() {\n  // Call a function repetatively with 0.1 Second interval\n  getData();\n}, 100); //100mSeconds update rate\n\nfunction getData() {\n  var xhttp = new XMLHttpRequest();\n  xhttp.onreadystatechange = function() {\n    if (this.readyState == 4 && this.status == 200) {\n      document.getElementById(\"ADCValue\").innerHTML =\n      this.responseText;\n    }\n  };\n  xhttp.open(\"GET\", \"readADC\", true);\n  xhttp.send();\n}\n</script>\n</html>

使用这个 Python 程序:

if __name__ == '__main__':
    with open(<filepath>) as html:
        contents = html.read().replace('"', r'\"')

    print(contents)
    print('')
    print(repr(contents))

当 "escaping" 双引号时,我得到了我想要的东西减去双反斜杠。我尝试了一些随机的事情,但所有的尝试要么去掉两个反斜杠,要么根本不改变字符串。

我只想在字符串中的所有双引号前添加一个反斜杠。这在 Python 中甚至可能吗?

您可以使用 str.translate 将麻烦的字符映射到它们的转义字符。由于 python 关于转义字符和引号字符的规则可能有点古怪,我只是强制使用它们以保持一致性。

# escapes for C literal strings
_c_str_trans = str.maketrans({"\n": "\n", "\"":"\\"", "\":"\\"})

if __name__ == '__main__':
    with open(<filepath>) as html:
        contents = html.read().translate(_c_str_trans)

    print(contents)
    print('')
    print(repr(contents))