Search code examples
pythonstring-formatting

Don't understand cause of "IndexError: tuple index out of range" when formatting string


I looked at similar questions having this IndexError but didn't find an explanation to my case. Can someone explain why I get the error?

The following code

mySF2[0]=['000browser', '1', 'Floor', '0.92', '1.74', 'con', 'None']

insertfmt = ' '.join([
"INSERT INTO mySchema.myTable_{}_name (col1, col2, col3, col4, col5, col6)",  
"VALUES ({}, {}, NULLIF({},'None')::decimal, NULLIF({},'None')::decimal, {}, NULLIF({},'None')::int)"
         ])

insertfmt.format(mySF2[0])

Gives this error

IndexError: tuple index out of range

However, I count 7 placeholders (i.e. curly brackets {}) and 7 items to input. Why the error then?


Solution

  • str.format() accepts a variable number of arguments corresponding to the number of "holes" in your format string. In your case, you are passing in a single argument (a list) to .format(), which causes an error because it expects seven arguments.

    To pass in an array to a function as separate arguments, you need to use the * operator like so:

    insertfmt.format(*mySF2[0])