I am trying to do an insert in postgres through python (psycopg2). I need to include both single and double quotes in the string that does the insert. This is my code:
You can simplify your code a lot:
table_name = "my_table"
values_to_insert = ["O'neal", '"The Film "']
column_name_list = ["UpperAndLowercase", "otherColumn"]
print "INSERT INTO {} ".format(table_name) + ", ".join(['"{}"'.format(i) for i in column_name_list]) + " VALUES(" + ", ".join(["'''{}'''".format(i) for i in values_to_insert])
Outputs your desired result:
INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "'''
Are you using the python interpreter? Notice how x looks vs print(x) below.
If I put your code in a script and print it out it looks fine to me.
>>> table_name = "my_table"
>>> values_to_insert = ["""O'neal""", '''"The Film "''']
>>> column_name_list = ["UpperAndLowercase", "otherColumn"]
>>>
>>> x = "INSERT INTO {} ".format(table_name) + ", ".join(['''"{}"'''.format(i) for i in
... column_name_list]) + " VALUES(" + ", ".join("""'''{}'''"""
... .format(i).encode("utf-8").decode('unicode_escape') for i in values_to_insert)
>>> x
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES(\'\'\'O\'neal\'\'\', \'\'\'"The Film "\'\'\''
>>> print(x)
INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "'''
>>>
Note also that you can just use triple """
instead of also using '''
s = """ this has 'single' and "double" quotes """