In Python I am trying to replace all instances of " in a string with \", using the standard string replace() method.
So if I have as input test string "hello", my expected output should be test string \"hello\"
However, I'm not getting expected results, with a variety of attempts.
I would think that having \\ would print a single \, since we are escaping the escape character. We can prove this by print('\\') which prints a \.
If I run the following code on a Python prompt, I get the expected result:
my_string = 'test string "hello"'
my_string = my_string.replace('"', f'\\"')
However, if I either save the string to a file, or print it in a Jupyter notebook, I do not get the expected output:
my_string = 'test string "hello"'
with open('test_file.txt', "w") as f:
f.write(my_string.replace('"', f'\\"'))
This produces a text file with test string \\"hello\\".