Include both single quote and double quote in python string variable

后端 未结 2 447
暖寄归人
暖寄归人 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 "'''
    
    0 讨论(0)
  • 2021-01-29 15:47

    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 """
    
    0 讨论(0)
提交回复
热议问题