Python: Append to String N times

92 Views Asked by At

My script parses the directory for JSON files and creates tables in the database for each one. I am now working on importing the data from those files. In order to build the SQL query string with a variable length number of columns, I need to append the query string with %s for each column, before closing the query string with ")", and returning it to the import record function.

The working code looks like this :

TABLES[tablename] += (
    "INSERT INTO " + tablename + str(tuple(table[0].keys())).replace("'", "")
)

TABLES[tablename] += "\nVALUES\n("

And then the problematic portion :

    for key in table[0].keys():
        key = key  # just to shut the linter up...
        TABLES[tablename] += "%s, "

The linter complains that I am not using the variable "key". Which doesn't prevent it from working, but it suggests there is likely a better way to do this.

I tried this:

TABLES[tablename].extend("%s, ", len(table[0].keys()))

Which threw an exception that 'str' object has no attribute 'extend'

Is there no better way to str += "value" * x ?

1

There are 1 best solutions below

1
On BEST ANSWER

You can try the throwaway variable _ (someone else might have a better description) and check to see if your linter complains about not using that.

Something like:

for _ in table[0].keys():
  TABLES[tablename] += "%s, "