Python list is a data strucuture that stores multiple variables in a single variable. Lets say you have a string that are separated by comma not space and wants to convert comma seprated string to list then how you can do so. In this tutorial you will know How to convert comma separated string to list python using various methods.
Methods to convert comma separated string to list python
There are multiple ways to convert a comma-separated string to a list in Python. Here are a few methods:
Method 1: Using the split() method:
string = "apple,banana,grape"
my_list = string.split(",")
print(my_list)
Output
['apple', 'banana', 'grape']
Method 2: Using the split() method along with list comprehension
string = "apple,banana,grape"
my_list = [item for item in string.split(",")]
print(my_list)
Output
['apple', 'banana', 'grape']
Method 3: Using the split() method with map() function
string = "apple,banana,grape"
my_list = list(map(str, string.split(",")))
print(my_list)
Output
['apple', 'banana', 'grape']
Method 4: Using the CSV module
If the string contains more complex values (e.g., containing special characters or quotes), it’s better to use the CSV module. Here’s an example:
import csv
string = 'apple,"banana, mango","grape, pineapple"'
my_list = list(csv.reader([string], delimiter=',', quotechar='"'))[0]
print(my_list)
Output
['apple', 'banana, mango', 'grape, pineapple']
Conclusion
Somestime string may be seprated by the comma. If you want to break the strings using the comma then you have to use the above methods. All methods are useful and you have the choice to choose.
Leave a Reply