I'm looking to escape special characters in string for Python 2.7.
For example, if I have :
str = "You're the best "dog" on earth."
I would have :
str = "You\'re the best \"dog\" on earth."
I want it because I'm inserting strings in SQL database using pymySQL and I can't find a way to do this.
I guess escaping characters must be like this ? (not really sure) I also would find a way to do the reverse action remove escpaing characters.
You don't need to escape values for the purpose of SQL by hand! Let the database API take care of that.
Form a valid string literal in Python source code:
str = "You're the best \"dog\" on earth."
str = 'You\'re the best "dog" on earth.'
str = """You're the best "dog" on earth."""
These are all equivalent, you just need to escape the appropriate quotes that you're using as string literal terminators.
Use the database API correctly and don't worry about escaping. From the manual:
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
Escaping is handled by separating the query and values, not by adding backslashes.