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

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

本文关键字:转义 版本 转换 字符串 C++ 中将 Python      更新时间:2023-10-16

我正在尝试编写一个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>nn<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>nn<script>nsetInterval(function() {n  // Call a function repetatively with 0.1 Second intervaln  getData();n}, 100); //100mSeconds update ratennfunction 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))

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

我只想在字符串中的所有双引号之前添加一个反斜杠。这在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))