簡體   English   中英

在 python 字符串變量中包括單引號和雙引號

[英]Include both single quote and double quote in python string variable

我正在嘗試通過 python (psycopg2) 在 postgres 中進行插入。 我需要在插入的字符串中包含單引號和雙引號。 這是我的代碼:

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)

我期待這個:

'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "''''

但是得到了這個:

'INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES(\'\'\'O\'neal\'\'\', \'\'\'"The Film "\'\'\''

你在使用 python 解釋器嗎? 請注意下面的 x 與 print(x) 的外觀。

如果我將您的代碼放在腳本中並將其打印出來,對我來說看起來不錯。

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

另請注意,您可以只使用三個"""而不是也使用'''

s = """ this has 'single' and "double" quotes """

您可以大大簡化您的代碼:

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])

輸出你想要的結果:

INSERT INTO my_table "UpperAndLowercase", "otherColumn" VALUES('''O'neal''', '''"The Film "'''

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM