Reputation: 1016
The following code produces a file with content test\\nstring
, but I need the file to contain test\nstring
. I can't figure out a way to replace the \\
symbol either.
s = "test\nstring"
with open('test.txt', 'w') as f:
f.write(s)
How can I make sure that the file contains only \n
instead of \\n
?
Upvotes: 0
Views: 87
Reputation: 119
The raw strings
may help
s = r"test\nstring"
with open('test.txt', 'w') as f:
f.write(s)
Upvotes: 1
Reputation: 3460
Besides of escaping and raw string, you can encode it (2 or 3) with 'string_escape'
:
s = "test\nstring".encode('string_escape')
with open('test.txt', 'w') as f:
f.write(s)
Upvotes: 1
Reputation: 3097
use s = "test\\nstring"
I tried with the following code and worked.
s = "test\\nstring"
with open('test.txt', 'w') as f:
f.write(s)
and the test.txt
file contains
test\nstring
Upvotes: 1