String replacement with backslashes and inverted commas

Viewed 336

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

3 Answers

You're close. In order to do this, you must use a properly formatted escape character.

Perhaps this is what you're looking for?

Code:

my_string = 'test string "hello"'

with open('test_file.txt', "w") as foo:
    foo.write(my_string.replace('"', '\\"'))

Output:

# Written to new file test_file.txt

test string \"hello\"

Try this:

my_string = 'test string "hello"' 
my_string = my_string.replace('\"', ' \\" ')
print(my_string) 
my_string = 'test string "hello"'
my_string.replace('"', '\\"')

This thing works exactly fine, It's just the terminal which is showing you double slashes. Cause '\' is an escape sequence character. You can verify it like this:

>>len(my_string)
19
>>len(my_string.replace('"', '\\"'))
21

For the updated part: You can use something like this:

with open('test_file.txt', "w") as f:
    f.write(my_string.replace('"', '\\"'))

But Be aware that \" means just " whenever you read it from the file..

Related