OneBite.Dev - Coding blog in a bite size

escape a string in python

Code snippet on how to escape a string in python

my_string = "HelloWorld"
escaped_string = my_string.replace("'", "\\'")

This code snippet replaces any single quotation marks in the string my_string with an escaped version. By adding a backslash before the single quote we are telling python that this is just an ordinary character rather than a special character or a delimiter. After this code is run my_string would contain the string HelloWorld and escaped_string would contain the string HelloWorld with any instances of single quotation marks being replaced by an escaped version (\').

python