How To Convert Comma-Delimited String To A List In Python
A comma-delimited string is nothing but a string separated by commas. In Python, we can make use of in-built functions to separate a string based on a comma or some other delimiter and create a list with each separated value as the list item. In today’s post, we will look at the multiple ways in which we can convert a comma-delimited string to a list in Python.
Convert Comma-Delimited String to a List in Python
Below are some of the ways by which we can convert comma-delimited string to a list in Python:
- Using the string.split() method
- Using List Comprehension
- Using re module of Python
Convert Comma-Delimited String to a List Using string.split() method
The split() method of Python takes a delimiter like a comma as an argument and based on the delimiter, splits a string into a list. If no delimiter is provided, it splits the string on the basis of whitespaces.
Python3
#string cars = "Porsche, G Wagon, Mercedes, Audi, Range Rover" #use split function cars = cars.split( ',' ) print (cars) |
['Porsche', ' G Wagon', ' Mercedes', ' Audi', ' Range Rover']
Convert Comma-Delimited String to a List Using List Comprehension
A list comprehension in Python is nothing but a shorthand used to create lists with a very few lines of code. Here is how you can make use of list comprehensions to convert a comma separated string to a list in Python:
Python3
#string cars = "Porsche, G Wagon, Mercedes, Audi, Range Rover" #list comprehension cars = [i.strip() for i in cars.split( ',' )] print (cars) |
['Porsche', 'G Wagon', 'Mercedes', 'Audi', 'Range Rover']
Convert Comma-Delimited String to a List Using re Module
The re or regular expression module of Python contains the re.split() method that splits a string based on a pattern. In the code, you can see that the regular expression used for splitting the string is ‘r‘\s*, \s*’’. Here, the ‘\s*’ is looking for zero or more whitespace characters while the ‘,’ looks for a comma(,) in the given string. Further, the ‘\s*’ in the end also looks for zero or more whitespace characters.
Python3
#import the re module import re #string cars = "Porsche, G Wagon, Mercedes, Audi, Range Rover" #regex/regular expression cars = re.split(r '\s*,\s*' , cars) print (cars) |
['Porsche', 'G Wagon', 'Mercedes', 'Audi', 'Range Rover']
Contact Us