Python 在元组的最后一项后添加尾随逗号

Python 在元组的最后一项后添加尾随逗号,python,sqlite,Python,Sqlite,我使用的是sqlite3,它要求我们在元组的最后一项(值)后面加上尾随逗号。下面的示例应返回(2,3,)的预期输出。是否有一个内置函数可以处理此问题 args = 2, 3 print(args) # (2, 3) print((args,)) # ((2, 3),) sqlite3,在“John”之后不带尾随逗号 import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() c.execute("SELECT *

我使用的是sqlite3,它要求我们在元组的最后一项(值)后面加上尾随逗号。下面的示例应返回
(2,3,)
的预期输出。是否有一个内置函数可以处理此问题

args = 2, 3

print(args)
# (2, 3)

print((args,))
# ((2, 3),)
sqlite3,在“John”之后不带尾随逗号

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John'))
print(c.fetchall())
conn.close()

# sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
# current statement uses 1, and there are 4 supplied.
import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John',))
print(c.fetchall())
conn.close()

# [(1, 'John')]
sqlite3,在“John”后带尾随逗号

import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John'))
print(c.fetchall())
conn.close()

# sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
# current statement uses 1, and there are 4 supplied.
import sqlite3

conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT * FROM stocks WHERE first_name = ?", ('John',))
print(c.fetchall())
conn.close()

# [(1, 'John')]

这是不可能的。因为您使用的是元组,如果只有一个元素,则需要逗号。用括号[]代替括号()使用列表。

您的语句在以下细节方面有所不同:

('John')  ## this is not a tuple, it just evaluates to the string 'John'
('John',) ## this *is* a tuple, containing a string 'John' as its only element

但是,这种差异只在元组只有一个项的情况下存在

('John', 'Sue') == ('John', 'Sue',)

…是一个真正的语句,因为只要有多个项,该值就会明确地解析为元组;不需要尾随逗号。

sqlite3在哪里需要它?我有
sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用1,提供了3个
。我解决问题的方法是在元组的最后一部分添加一个尾随逗号。如果代码有问题,则需要显示代码。尾随逗号仅适用于1的元组element@joumaico,sqlite不需要后面的逗号
(2,3)
(2,3,)
完全相同;没有任何代码(包括sqlite)可以将它们区分开来。谢谢,我无意中
args=1,
将args设置为元组而不是字符串。我终于看到了确切的术语:
在Python中,包含单个值的元组必须包含逗号。例如,('abc')作为标量计算,而('abc',)作为元组计算。
谢谢Charles。