简体   繁体   中英

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

I'm trying to write a Python program that reads in a file and prints the contents as a single string as it would be escaped in a C++ format. This is because the string will be copied from Python output and pasted into a C++ program (C++ string variable definition).

Basically, I want to convert

<!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>

to this

<!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>

Using this Python program:

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

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

I get exactly what I want minus double backslashes when "escaping" the double quotes. I've tried a few random things, but all the attempts either get rid of both backslashes or don't change the string at all.

I simply want to add a single backslash before all the double quotes in my string. Is this even possible in Python?

You can use str.translate to map the troublesome characters to their escaped equivalents. Since python's rules on escape and quote characters can be a bit baroque, I've just brute forced them for consistency.

# 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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