1

I have a list of variables as:

listV = ['v1, 'v2', ...,'v200']

I want to do something of the following sort in a cleaner way:

q1 = 'insert into myTable ({}, {}, {},....{})'.format(listV)

My desired output will be:

q1 = 'insert into myTable (v1, v2, v3, ...., v200)'

For fewer number of variables, I am able to write a cleaner code but with 200 variables I am having difficulty creating cleaner code.

I need to create the q1 dynamically as the content of listV changes but the length of listV stays constant.

Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
Zanam
  • 3,540
  • 9
  • 42
  • 91
  • `', '.join(listV)`… – deceze Jun 04 '19 at 14:46
  • 2
    Obligatory [Bobby Drop Tables](https://xkcd.com/327/). You should use [parameterized](https://stackoverflow.com/questions/775296/mysql-parameterized-queries/775344#775344) [queries](https://stackoverflow.com/questions/1633332/how-to-put-parameterized-sql-query-into-variable-and-then-execute-in-python) or you're leaving yourself open to [SQL-injection attacks](https://stackoverflow.com/questions/601300/what-is-sql-injection). – pault Jun 04 '19 at 14:48
  • If I'm guessing correctly, you're trying to construct an SQL query. (If so, please confirm. If not, then ignore this comment.) This looks like an [xy problem](http://xyproblem.info/). You seem to be looking for direct/raw formatting, but there are better, easier, safer ways to construct SQL queries. – TrebledJ Jun 04 '19 at 15:03

5 Answers5

3
>>> listV = ['v1', 'v2', 'v200']
>>> q1 = 'insert into myTable'
>>> q1 = q1 + ' (' + ', '.join(listV) +  ')'
>>> q1
'insert into myTable (v1, v2, v200 )'
Supratim Haldar
  • 1,976
  • 2
  • 12
  • 24
2
listV = ['v1', 'v2', 'v200']
q1 = "insert into myTable ({})".format(", ".join(listV))
Olvin Roght
  • 5,080
  • 2
  • 11
  • 27
1

To save yourself some trouble, you can create the format string programatically as well.

listV = ["V1", "V2", "V3"]

n = len(listV)

fstring = "insert into myTable (" + "{}, " * (n-1) + "{})"

q1 = fstring.format(*listV) 
# The * unpacks the items in listV into separate arguments
print(q1)
# >>> insert into myTable (V1, V2, V3)
1

That's the way I can think of....

my_list = [1,2,3]
q = "insert into mytable ("
for i in range(0, len(my_list), 1):
    currNum = my_list[i]
    if i != len(my_list) - 1:
        q += str(currNum) + ","
    else:
        q += str(currNum)
q += ")"
print(q)

I'm a Python newbie -_-

lee john
  • 11
  • 3
1
listV = [i for i in range(200)]
q1 = str("insert into myTable (" + "{}, "*(len(listV)-1) + "{})").format(*listV)

As others have mentioned, string-formatting sql-queries leaves your database vulnerable for SQL-injections.

EDIT Olvyn Roght had a very nice answer! Here is an alternative version that also works with integers:

listV = [i for i in range(200)]
q1 = "insert into myTable ({})".format(str(listV)[1:-1])
Kent Martin
  • 225
  • 1
  • 10