Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

python - Add quotes to every list element

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...