Include both single quote and double quote in python string variable

后端 未结 2 448
暖寄归人
暖寄归人 2021-01-29 14:52

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:



        
2条回答
  •  一整个雨季
    2021-01-29 15:40

    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 "'''
    

提交回复
热议问题