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.
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].
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With