Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join a list of strings such that each string is within quotes and comma separated

Tags:

python

Consider that I have a list of customer names:

lst = ['John','Jack','Martin']

The desired output in a variable: 'John','Jack','Martin'

I can use something like ",".join(lst) and then more string formatting to achieve this. Is there any clear and more direct approach to this?

My idea is to pass the elements of a string in a SQL where clause.

like image 672
Maverick Avatar asked Sep 02 '15 14:09

Maverick


People also ask

How do you convert a list to a string separated by comma in Python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].

How do I join a list of words into a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I concatenate two strings with a comma in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


1 Answers

Do not use this for SQL query generation. Use the database driver SQL parameters instead. You cannot hope to properly escape your way out of SQL injection attacks otherwise.

If you need to use a WHERE .. IN .. test, generate placeholders:

query = 'SELECT * FROM table WHERE column IN ({})'.format(','.join(['%s'] * len(lst)))
cursor.execute(query, lst)

For everything else, use a list comprehension to add the quotes to the values, then join the results with commas:

', '.join(['"{}"'.format(value) for value in lst])

Demo:

>>> lst = ['John','Jack','Martin']
>>> ', '.join(['"{}"'.format(value) for value in lst])
'"John", "Jack", "Martin"'
>>> print ', '.join(['"{}"'.format(value) for value in lst])
"John", "Jack", "Martin"

This will consistently use " double quotes; simply use "'{}'" as the template if you must have single quotes instead.

like image 177
Martijn Pieters Avatar answered Oct 14 '22 12:10

Martijn Pieters