首页 > 解决方案 > 用反斜杠和反逗号替换字符串

问题描述

在 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\\".

标签: pythonreplace

解决方案


你很近。为此,您必须使用格式正确的转义字符

也许这就是你要找的?

代码:

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\"

推荐阅读