2024-05-19 12:24:23 发布
网友
下面的代码生成一个内容为test\\nstring的文件,但我需要该文件包含test\nstring。我也找不出替换\\符号的方法。你知道吗
test\\nstring
test\nstring
\\
s = "test\nstring" with open('test.txt', 'w') as f: f.write(s)
如何确保文件只包含\n而不是\\n?你知道吗
\n
\\n
使用s = "test\\nstring" 我尝试了以下代码并成功了。你知道吗
s = "test\\nstring"
s = "test\\nstring" with open('test.txt', 'w') as f: f.write(s)
而test.txt文件包含
test.txt
raw strings可能会有所帮助
raw strings
s = r"test\nstring" with open('test.txt', 'w') as f: f.write(s)
除了转义和原始字符串之外,您还可以使用'string_escape'对其进行编码(2或3):
'string_escape'
s = "test\nstring".encode('string_escape') with open('test.txt', 'w') as f: f.write(s)
使用
s = "test\\nstring"
我尝试了以下代码并成功了。你知道吗而
test.txt
文件包含raw strings
可能会有所帮助除了转义和原始字符串之外,您还可以使用
'string_escape'
对其进行编码(2或3):相关问题 更多 >
编程相关推荐