Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add quotes to every list element

Tags:

python

I'm very new to python. I need a simple and clear script to add quotes to every list elements. Let me explain more. Here is the my code.

parameters = ['a', 'b', 'c'] query = "SELECT * FROM foo WHERE bar IN (%s)" % (', '.join(parameters)) 

I want to use this to query. But result is invalid query. Here is the result.

SELECT * FROM foo WHERE bar IN (a, b, c, d) 

I want to like this:

SELECT * FROM foo WHERE bar IN ('a', 'b', 'c', 'd') 

How to add quotes while joining elements.

like image 623
Zeck Avatar asked Jul 19 '11 00:07

Zeck


People also ask

How do I add a quote to a list in Excel?

Use "CHAR(34)" within formulas where you need to output quotation marks. For example, to add quotes around the text in cell A1, you would type "=CHAR(34)&A1&CHAR(34)" in an empty cell.


2 Answers

A naive solution would be to iterate over your parameters list and append quotes to the beginning and end of each element:

(', '.join('"' + item + '"' for item in parameters)) 

Note: this is vulnerable to SQL injection (whether coincidental or deliberate). A better solution is to let the database quote and insert these values:

query = "SELECT * FROM foo WHERE bar IN (%s)" % ','.join('?' * len(params)) cursor.execute(query, params) 

It's easier to read and handles quoting properly.

like image 122
Blender Avatar answered Sep 21 '22 01:09

Blender


For simple parameters, the following should work:

query = "SELECT * FROM foo WHERE bar IN %s" % repr(tuple(map(str,parameters))) 

This may break down when the parameter names themselves include quotes, as the escaping rules are different.

like image 20
Sam Ruby Avatar answered Sep 19 '22 01:09

Sam Ruby