How to convert comma-separated string to list in Python

In this tutorial, we will learn how to convert a comma separated string to a list in Python. For that, we will use a built-in function split().¬†So let’s dive right into it.

Comma-separated string to list in Python

First of all, we will store a comma-separated string in a variable comma_string.

comma_string="Apple,Banana,Litchi,Mango"

We now want to convert comma_string to a list. In order to do that, we will use a method split().

split() splits a string into a list. It takes delimiter or a separator as the parameter.

Syntax:
string_name.split(separator)

Here, the separator is a comma(,). We store the list returned by split() method in a variable string_list.

string_list=comma_string.split(",")

Since we got what we needed, so we print the value of string_list.

print("Comma separated string in list:",string_list)

Finally, Our code looks like this.

comma_string="Apple,Banana,Litchi,Mango"
string_list=comma_string.split(",")
print("Comma separated string in list:",string_list)

And the output,

Comma separated string in list: ['Apple', 'Banana', 'Litchi', 'Mango']

I would recommend you all to learn about built-in functions provided by Python because they help in reducing the complexity of a program and also the code length.

All the best!

Also, learn,

Leave a Reply

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