Convert a comma-separated string to a List in Python

This tutorial will discuss about unique ways to convert a comma-separated string to a list in Python.

Table Of Contents

Split the string by comma

String class in python has a method split(). It accepts an argument as delimeter, and returns a list of the words in the string, by separating them using the given delimiter string. To split comma-separated string to a list, pass “,” as argument in the split() method of string. It will return a list of strings.

Let’s see the complete example,

strValue = "'sample', 11,24, 56, 23, This, is, 67, a, 80"

#  Convert a comma-separated string to a List
listOfElements = strValue.split(',')

print(listOfElements)

Output

["'sample'", ' 11', '24', ' 56', ' 23', ' This', ' is', ' 67', ' a', ' 80']

Split the string by comma and strip extra spaces

In the above example, we converted a comma-separated string to a list. But some of the strings in list has extra spaces around them like, ‘ 56’, ‘ is’ etc. If you dont want these extra spaces on both the sides of splitted strings in list, then you can call the strip() method on each string before storing them into the list.

Let’s see the complete example,

strValue = "'sample', 11,24, 56, 23, This, is, 67, a, 80"

# Convert a comma-separated string to a List
listOfElements = [elem.strip() for elem in strValue.split(',')]

print(listOfElements)

Output

["'sample'", '11', '24', '56', '23', 'This', 'is', '67', 'a', '80']

The split() method returned a list of strings. Then we iterated over all the strings in list and called the strip() on each string inside a List Comprehension. It returned a list of trimmed strings i.e. none of the string in list has any extra spaces on both sides.

Split the string by comma and handle empty string

If the given string is empty, then we need to create an empty list instead of splitting it.

Let’s see the complete example,

strValue = ""

#  Convert a comma-separated string to a List
listOfElements = strValue.split(',') if strValue else []

print(listOfElements)

Output

[]

Summary

We learned how to convert a comma-separated string to a List in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top