Insert a backslash `\` before quotes in a String in Python


Borislav Hadzhiev

Last updated: Sep 20, 2022


Photo from Unsplash

Insert a backslash \ before quotes in a String in Python #

Use the str.replace() method to insert a backslash before the quotes in a string, e.g. my_str = my_str.replace("'", "\\'"). The str.replace() method will insert a backslash before each quote by replacing the quotes with a backslash followed by a quote.
my_str = "bobby'hadz" my_str = my_str.replace("'", "\\'") print(my_str) # 👉️ bobby\'hadz

The code sample inserts a backslash before every single quote in the string.

Make sure to alternate between single and double quotes, otherwise, you'd terminate the string prematurely.

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Here is an example that inserts a backslash before every double quote in a string.
my_str = 'bobby"hadz' my_str = my_str.replace('"', '\\"') print(my_str) # 👉️ bobby\"hadz
The backslash \ character has a special meaning in Python - it is used as an escape character (e.g. \n or \t).

By adding a second backslash, we treat the backslash (\) as a literal character.

If you have access to the definition of the string, you can also prefix it with r.
my_str = r"bobby\'hadz" print(my_str) # 👉️ bobby\'hadz

Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.