无法使用列表格式化字符串

时间:2014-05-01 11:13:15

标签: python string formatting

我有这两个字段

s = "SELECT * FROM %s WHERE %s = %s ORDER BY %s;"
data = ['students', 'age', 12, 'desc']

从我看到的,我在列表中计算了足够的元素来格式化字符串。 但是

print s.format(data)
#or
print s % tuple(data)
#or
print s % data

返回TypeError: not enough arguments for format string

1 个答案:

答案 0 :(得分:2)

只需将列表转换为元组,就像这样

s, l = "SELECT * FROM %s WHERE %s = %s ORDER BY %s;",['students','age',12,'desc']
print s % tuple(l)
# SELECT * FROM students WHERE age = 12 ORDER BY desc;

Online Demo