Python program to convert list of string to comma separated string


Python is derived from many other languages including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and UnixShell, and many other scripting languages.

Now, as we know this article is all about converting a list of strings to comma-separated strings. Before diving deep into it, it’s necessary to know in detail about strings and lists in python. Let’s move ahead with the topic and understand them in detail. Starting off with string.

What is a String?

Python strings are sequences of characters, which means they are ordered collections of characters.

"This is a string."
'This is also a string.'

Strings in Python are arrays of bytes representing Unicode characters. Python strings are “immutable” which means they cannot be changed after they are created. This means that its internal data elements, the characters, can be accessed, but cannot be replaced, inserted, or removed for input and output. A string is a data structure. A data structure is a compound unit that consists of several other pieces of data. A string is a sequence of zero or more characters.

A string length is the number of characters it contains. Python’s len() function is used to return the length of the string.

Syntax

len(str)

Example

len("WELCOME")

Output

7

Each character occupies a position in the string. The positions of a string’s characters are numbered from 0, on the left, to the length of the string minus 1, on the right. Now, moving on to the topic of the list.

What is a List?

A list is a collection of items in a particular order. You can make a list that includes the letters of the alphabet, and the digits from 0–9. In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.

Example

bicycles = ['trek', 'Cannondale', 'redline', 'specialized']
print(bicycles)

Output

['trek', 'Cannondale', 'redline', 'specialized']

A list is a value that contains multiple values in an ordered sequence. The term list value refers to the list itself (which is a value that can be stored in a variable or passed to a function like any other value), not the values inside the list value. A list value looks like this: ['cat', 'bat', 'rat', 'elephant']. Values inside the list are also called items. Items are separated with commas (that is, they are comma-delimited).

Here we’ll look at how to change a string into a comma-separated string. It is important to keep in mind that the given string can be a list of strings as well.

Converting Python List Into A Comma-Separated String

When we convert a list of strings into a comma-separated string, it results in a string where each element of the list is separated by a comma.

For example, if we convert [“my”, “name”, “is”, “Nikita”] to a comma-separated string, it will result in “my, name, is, Nikita”.

Using the join() Function

An iterable component are combined by the join() function, which also returns a string. The character that will be utilized to separate the string's elements must be specified.

Here we are supposed to create a comma-separated string, so we will use the comma as a separator.

Example

The following program creates a list and joins them together into one comma separated string by using join() function.

List = ["Apple", "Banana", "Mango", "Orange"]
String = ', '.join(List)
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)

Output

List of String:
['Apple', 'Banana', 'Mango', 'Orange']
Comma Separated String:
Apple, Banana, Mango, Orange

The above approach is only applicable to a list of strings.

To work with a list of integers or other elements, we can use list comprehension and the str() function. We can quickly run through the elements with list comprehension in a single line using the for loop, then convert each element to a string using the str() function.

Example

In the following program, a list of strings is created and stored in the variable List. A new string is then created by joining each element from the list with a comma as a separator and stored in the variable String.

List = ['235', '3754', '856', '964']
String = ', '.join([str(i) for i in List])
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235, 3754, 856, 964

Using the map() function, we can also eliminate list comprehension. By applying the str() function to each element of the list, the map() function can be used to convert all elements of the list to strings.

Example

Using the map() function, we can also eliminate list comprehension. By applying the str() function to each element of the list, the map() function can be used to convert all elements of the list to strings.

List = ['235', '3754', '856', '964']
String = ', '.join(map(str,List))
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235, 3754, 856, 964

Using the StringIO Module

The StringIO object is comparable to a file object, however it works with text in memory. It can be imported directly in Python 2 by utilising the StringIO module. It was saved in the io module in Python 3.

Example

To write the list as a comma-separated row for a CSV file in the StringIO object, we can use the csv.writerow() function. To do so, we must first create a csv.writer object. Using the getvalue() function, we can then store the contents of this object in a string.

import io
import csv
List = ['235', '3754', '856', '964']
String_io = io.StringIO()
w = csv.writer(String_io)
w.writerow(List)
String = String_io.getvalue()
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)

Output

List of String:
['235', '3754', '856', '964']
Comma Separated String:
235,3754,856,964

We may also use the unpack operator with the print() function. The unpack operator * unpacks all of the elements of an iterable and saves them in the StringIO object via the file parameter in the print() function.

Example

A list is created with the values 8, 9, 4 and 1. A StringIO object String_io is then created, allowing the string to be treated as a file. The list is printed as a StringIO object with file=String_io and sep=',' and end=''. This separates each element in the list with a comma and does not add a new line or character to the end of the line. The string stored in string_io is retrieved by the getvalue() method and stored in a variable named "String".

import io
List = [8,9,4,1]
String_io = io.StringIO()
print(*List, file=String_io, sep=',', end='')
String = String_io.getvalue()
print("List of String:")
print(List)
print("Comma Separated String:")
print(String)

Output

List of String:
[8, 9, 4, 1]
Comma Separated String:
8,9,4,1

Conclusion

In this article, we have discussed about different methods to convert a list of string to comma separated string.

Updated on: 21-Apr-2023

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements