Skip to content
Advertisement

Ignoring escape characters in python

I am trying to insert a title into a DB. Sometimes the title has quotes and it throws an error.

I can’t replace quotes with a ” because it thinks that I am escaping the quote.

sql = 'UPDATE `table_name` SET `title`="{}";'

title = 'A "Title" With Quotes'

sql.format(title.replace('"','"'))

This replaces the quotes with more quotes so it changes nothing.

'UPDATE `table_name` SET `title`="A "Title" With Quotes";'

If I try to escape the backslash it doesn’t escape anything.

sql.format(title.replace('"','\"'))

'UPDATE `table_name` SET `title`="A \"Title\" With Quotes";'

Advertisement

Answer

The best way to do this is using triple quotes, that’s interprets text inside as a string:

sql = """UPDATE `table_name` SET `title`="{}";""" 

you either can format It was you want:

sql = """UPDATE `table_name` SET `title`="{}";""".format('A \"B\"')
print(sql)

output:

UPDATE `table_name` SET `title`="A "B"";

Works on MySQL

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement