[英]Include both single quote and double quote in python string variable
I am trying to do an insert in postgres through python (psycopg2).我正在尝试通过 python (psycopg2) 在 postgres 中进行插入。 I need to include both single and double quotes in the string that does the insert.
我需要在插入的字符串中包含单引号和双引号。 This is my code:
这是我的代码:
table_name = "my_table"
values_to_insert = ["""O'neal""", '''"The Film "''']
column_name_list = ["UpperAndLowercase", "otherColumn"]
"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)
I expected this:我期待这个:
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "''''
But got this:但是得到了这个:
'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES(\'\'\'O\'neal\'\'\', \'\'\'"The Film "\'\'\''
Are you using the python interpreter?你在使用 python 解释器吗? Notice how x looks vs print(x) below.
请注意下面的 x 与 print(x) 的外观。
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 """
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 "'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.