python - 用反斜杠和反逗号替换字符串
问题描述
在 Python 中,我尝试使用标准字符串方法"
将字符串中的所有实例替换为 。\"
replace()
所以如果我有输入test string "hello"
,我的预期输出应该是test string \"hello\"
但是,通过各种尝试,我没有得到预期的结果。
我认为 have\\
会打印一个\
,因为我们正在转义转义字符。我们可以证明这一点,print('\\')
它打印 a \
。
如果我在 Python 提示符下运行以下代码,我会得到预期的结果:
my_string = 'test string "hello"'
my_string = my_string.replace('"', f'\\"')
但是,如果我将字符串保存到文件中,或者在 Jupyter 笔记本中打印,我不会得到预期的输出:
my_string = 'test string "hello"'
with open('test_file.txt', "w") as f:
f.write(my_string.replace('"', f'\\"'))
这会生成一个带有test string \\"hello\\"
.
解决方案
你很近。为此,您必须使用格式正确的转义字符。
也许这就是你要找的?
代码:
my_string = 'test string "hello"'
with open('test_file.txt', "w") as foo:
foo.write(my_string.replace('"', '\\"'))
输出:
# Written to new file test_file.txt
test string \"hello\"
推荐阅读
- java - 如何按行分解一维数组?
- c# - ASP.NET Core - 调用控制器 HTTP 端点总是导致“错误请求”
- docker - 如何使用秘密中的 ssh 密钥将私有 git 存储库克隆到 kubernetes pod 中?
- sql - Oracle 层次总和(叶子到根的距离)
- matlab - 使用 imread 从 windows 读取图像
- java - ARCore TransformableNode 拖动后将 localPosition 设置为 [x=0.0, y=0.0, z=0.0]
- javascript - 将 NodeJS 与电子应用程序一起打包
- aem - 在 AEM 中激活内容/页面和发布页面有什么区别?
- powershell - 使用 PowerShell 按邮箱大小对 csv 输出文件进行排序
- dependency-injection - 如何订阅 .net Core 中的事件?