我编写了一个函数来创建 SQL 查询的 VALUES
部分:
def query_values(data_iterator):
return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
) for data_row in data_iterator
),
当我调用这个函数并打印结果时,得到的是:
query_values:
('\n("801",\n"printer",\n"barcode printer")\n,\n\n("844",\n"laptop",\n"windows")\n,\n\n("997",\n"printer",\n"barcode printer")\n',)
内容在一行中显示,而不是换行,因为\n
会被显示出来。
最初我只有一个\n
,但后来我插入了多个,只是想看看它们是否会被显示出来。
第二个问题是整体周围有括号,而我不想要。
我思考了这两个问题,然后找到了第二个问题的解决方案:
我的函数末尾有一个逗号。逗号导致函数返回一个元组,而不是单个字符串。
我去掉了逗号:
def query_values(data_iterator):
return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
) for data_row in data_iterator
)
并且那个修复两个问题. 现在的输出是:
query_values:
("801",
"printer",
"barcode printer")
,
("844",
"laptop",
"windows")
,
("997",
"printer",
"barcode printer")
我加回了逗号,这样就显示出了\n
。我去掉逗号后,文本又变成了多行。
我去掉了多余的\n
,现在我得到了我想要的结果:
query_values:
("801","printer","barcode printer"),
("844","laptop","windows"),
("997","printer","barcode printer")
所以,我的代码可以正确运行,但我对旧版本的代码中显示的 \n
字符感到完全困惑。为什么会出现这种情况?
更新:
一些回答关注于我为什么得到一个元组,但那不是我的问题。为什么会显示 /n
?
tuple
的__repr__
(如果未定义__str__
)会在其元素上调用__repr__
(https://github.com/python/cpython/blob/fc96e5474a7bda1c5dec66420e4467fc9f7ca968/Objects/tupleobject.c#L298)。 - Solomon Ucko__str__
吗?对于一个元组t
,我尝试了t.__str__()
,结果和t.__repr__()
一样。我不知道如何检查__str__()
是否未定义或者定义为与__repr__
相同。 - Granny Aching