我正在构建一个选择查询并以编程方式向其中添加元素。问题是我需要值元组有一个尾随逗号。我该怎么做?
def build_search_query(user_list, make, model, price_min, price_max):
sql = """SELECT * FROM mycolumn WHERE user_id = %s, """
for i, d in enumerate(user_list):
if not i == 0: #skip first user because its already in sql
next_user = "OR user_id = %s, "
sql += next_user
age_str = "AND age = %s, "
height_str = "AND height = %s, "
price_min_str = "AND price > %s, "
price_max_str = "AND price < %s "
sql += age_str
sql += height_str
sql += price_min_str
sql += price_max_str
tuple1 = tuple(user_list)
tuple2 = (age, height, price_min, price_max,)
values = tuple1 + tuple2 #this is where I need the trailing comma
return sql, values
最佳答案
很简单,你不能。 值 是元组的内部表示。因此,它没有括号和逗号:这些只是为了方便人类阅读。
根据定义,元组不有尾随逗号。由于您返回的是值,而不是打印图像(输出的字符串表示形式),因此我不完全确定从这里引导您到哪里。
关于Python以编程方式将尾随逗号添加到元组的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461429/