Python – Convert List to CSV String

Convert List to CSV String

To convert a given list of values to a CSV (Comma Separated Value) string in Python, call join() method on the separator string, and pass the list as argument.

The string join() method join the given list of values into a string with the separator string in between the elements.

The syntax of the expression that returns a CSV string from a given list of values x is

','.join(x)

Note: If the elements in list are of not string type, join() method can raise TypeError. Before passing the given list as argument to join() method, convert the elements to string type.

Examples

1. Convert list of string values to CSV string

In the following example, we take a list of strings in x, and convert this list into a CSV string.

Python Program

x = ['apple', 'banana', 'cherry']
output = ','.join(x)
print(output)
Run Code Copy

Output

apple,banana,cherry

2. Convert list of integer values to CSV string

In the following example, we take a list of integers in x, and convert this list into a CSV string.

Since, the elements are not of string type, we convert them to string before passing the list as argument to join() method.

Python Program

x = [21, 14, 44, 8, 62]

# Convert integer values to string values
x = [str(value) for value in x]

# Convert list to CSV string
output = ','.join(x)
print(output)
Run Code Copy

Output

21,14,44,8,62

Summary

In this tutorial of Python Examples, we learned how to convert a list of values to a CSV string using join() method, with the help of examples.

Related Tutorials

Code copied to clipboard successfully 👍