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.

Answer from Martijn Pieters on Stack Overflow
🌐
Delim
delim.co
Free Online Comma Separating Tool
A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values. Convert a list of zipcodes in a spreadsheet into a comma-separated list that you can put in a WHERE IN() block to run reports!
Discussions

c# - How to convert List<string> into String of Comma Separated Quotes from List - Stack Overflow
I am trying to convert a list of strings into a comma separated with quotes variable,I can only join them as comma separated but can't put quotes around each of the entries in the list..can anyone More on stackoverflow.com
🌐 stackoverflow.com
linux - Turning separate lines into a comma separated list with quoted entries - Unix & Linux Stack Exchange
I have the following data (a list of R packages parsed from a Rmarkdown file), that I want to turn into a list I can pass to R to install: d3heatmap data.table ggplot2 htmltools htmlwidgets More on unix.stackexchange.com
🌐 unix.stackexchange.com
January 17, 2017
Converting a list into comma separated and add quotes in python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
July 30, 2018
python - convert a list into a single string consisting with double quotes and separated by comma - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
October 29, 2017
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert a python list to a quoted, comma-separated string
5 Best Ways to Convert a Python List to a Quoted, Comma-Separated String - Be on the Right Side of Change
February 20, 2024 - For those who like one-liners, Python’s str.translate() method can convert a list to a quoted, comma-separated string with a single expression—albeit at the cost of readability for those unfamiliar with translate() and mapping tables.
🌐
Capitalize My Title
capitalizemytitle.com › home › tools › online comma separator – convert list to csv (column to comma)
Convert Column to Comma Separated List
In the column next to the column you want to convert to a comma-separated string, enter the cell reference and (&”,”) without the paratheses.
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-convert-list-into-string-with-commas-exampleexample.html
Python Convert List into String with Commas Example - ItSolutionstuff.com
October 30, 2023 - If you need to see an example of python convert list into string with commas. you can understand the concept of python convert list to string comma separated. This post will give you a simple example of python convert list to comma separated string with quotes.
Top answer
1 of 8
37

You can add quotes with sed and then merge lines with paste, like that:

sed 's/^\|$/"/g'|paste -sd, -

If you are running a GNU coreutils based system (i.e. Linux), you can omit the trailing '-'.

If you input data has DOS-style line endings (as @phk suggested), you can modify the command as follows:

sed 's/\r//;s/^\|$/"/g'|paste -sd, -
2 of 8
12
Using awk:
awk 'BEGIN { ORS="" } { print p"'"'"'"$0"'"'"'"; p=", " } END { print "\n" }' /path/to/list
Alternative with less shell escaping and therefore more readable:
awk 'BEGIN { ORS="" } { print p"\047"$0"\047"; p=", " } END { print "\n" }' /path/to/list
Output:
'd3heatmap', 'data.table', 'ggplot2', 'htmltools', 'htmlwidgets', 'metricsgraphics', 'networkD3', 'plotly', 'reshape2', 'scales', 'stringr'
Explanation:

The awk script itself without all the escaping is BEGIN { ORS="" } { print p"'"$0"'"; p=", " } END { print "\n" }. After printing the first entry the variable p is set (before that it's like an empty string). With this variable p every entry (or in awk-speak: record) is prefixed and additionally printed with single quotes around it. The awk output record separator variable ORS is not needed (since the prefix is doing it for you) so it is set to be empty at the BEGINing. Oh and we might our file to END with a newline (e.g. so it works with further text-processing tools); should this not be needed the part with END and everything after it (inside the single quotes) can be removed.

Note

If you have Windows/DOS-style line endings (\r\n), you have to convert them to UNIX style (\n) first. To do this you can put tr -d '\015' at the beginning of your pipeline:

tr -d '\015' < /path/to/input.list | awk […] > /path/to/output

(Assuming you don't have any use for \rs in your file. Very safe assumption here.)

Alternatively, simply run dos2unix /path/to/input.list once to convert the file in-place.

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-lists-to-comma-separated-strings-in-python
Convert Lists to Comma-Separated Strings in Python - GeeksforGeeks
July 23, 2025 - In this article, we will explore three different approaches to make a comma-separated string from a list of strings in Python.
🌐
Usefmtly
usefmtly.com › home › tools › list tools › list to comma separated
List to Comma Separated — Free Online List Converter | usefmtly
March 9, 2026 - Convert a list to comma-separated values, semicolons, pipes, tabs, or custom delimiters. Trim whitespace, add quotes, and copy results for spreadsheets fast.
🌐
ExcelDemy
exceldemy.com › home › excel formulas › how to convert a column into a comma separated list with single quotes – 5 methods
How to Convert a Column into a Comma Separated List With Single Quotes - 5 Methods - ExcelDemy
August 9, 2024 - Enter the formula in C5. =CONCATENATE("'",B5,"',", "'",B6,"',", "'",B7,"',","'",B8,"',","'",B9,"'") ... The CONCATENATE function will take strings and join them to make a large text.
🌐
Baeldung
baeldung.com › home › java › java string › convert a list to a comma-separated string
Convert a List to a Comma-Separated String | Baeldung
July 2, 2025 - String commaSeparatedUsingCollect = arraysAsList.stream() .collect(Collectors.joining(",")); assertThat(commaSeparatedUsingCollect).isEqualTo("ONE,TWO,THREE"); In our next example, we’ll see how to use the map() method to convert each object of the list into a String and then apply the methods collect() and Collectors.joining():
🌐
ASPSnippets
aspsnippets.com › questions › 866059 › Convert-genetic-List-to-comma-separated-string-enclosed-within-quotes-using-C-and-VBNet
Convert genetic List to comma separated string enclosed within quotes using C and VBNet
October 31, 2014 - Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load Dim list1 As New List(Of String)() list1.Add("option1") list1.Add("option2") list1.Add("option3") Dim allProductId As String = "" For Each s As String In list1 allProductId += (Convert.ToString("'") & s) + "', " Next allProductId = allProductId.Remove(allProductId.Length - 2) End Sub
🌐
OneUptime
oneuptime.com › home › blog › how to convert list to string in python
How to Convert List to String in Python
January 25, 2026 - # Simple CSV line data = ['John', 'Doe', '30', 'Engineer'] csv_line = ','.join(data) print(csv_line) # 'John,Doe,30,Engineer' # Handle values with commas by quoting def to_csv_line(values): """Convert list to properly quoted CSV line.""" quoted = [] for v in values: s = str(v) if ',' in s or '"' in s or '\n' in s or '\r' in s: s = '"' + s.replace('"', '""') + '"' quoted.append(s) return ','.join(quoted) data = ['John', 'Doe, Jr.', 'New York'] print(to_csv_line(data)) # 'John,"Doe, Jr.",New York' For proper CSV handling, use the csv module. import csv from io import StringIO data = ['John', 'Doe, Jr.', 'New York'] output = StringIO() writer = csv.writer(output) writer.writerow(data) result = output.getvalue().strip() print(result) # 'John,"Doe, Jr.",New York'
🌐
AllTextConverters
alltextconverters.com › home › list to comma separated
List to Comma Separated (Lines to CSV) | AllTextConverters
Convert a line-based list into a comma-separated line instantly. Trims whitespace, ignores blank items, preserves order, and runs locally in your browser. Copy, export CSV, or download the result.