Saphire
Saphire

Reputation: 1930

Can't format string with a list

I have these two fields

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

From what I see, I count enough elements in the list to format the string. But

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

returns TypeError: not enough arguments for format string

Upvotes: 1

Views: 50

Answers (1)

thefourtheye
thefourtheye

Reputation: 239683

Just convert the list to tuple, like this

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

Upvotes: 2

Related Questions