To convert comma-delimited string to a list in Python, split the string with the str.split()
method.
For example:
string = "A,B,C,D,E,F,G" string_list = string.split(",") print(string_list)
Output:
['A', 'B', 'C', 'D', 'E', 'F', 'G']
This results in a list of the parts of the strings that were separated by commas.
Don’t Forget to Handle Empty Strings
Using the above approach on an empty string returns a list with one empty string. This is not what you would expect. Instead, the list should be empty if the string is empty.
To handle the case of an empty string, slightly modify the previous approach:
string = "" string_list = string.split(",") if string else [] print(string_list)
Output:
[]
Let’s also take a look at what you can do if the string contains both strings and integers.
How to Convert a Comma-Delimited String with Integers and Characters to a List
If you have a string that represents both integers and strings, you may want to
- Keep the strings as strings.
- Cast the integer strings to real integers.
To do this, you can use a regular for loop like this:
string = "1,B,C,3,E,5,6" string_list = [] for item in string.split(","): if item.isdigit(): string_list.append(int(item)) else: string_list.append(item) print(string_list)
Output:
[1, 'B', 'C', 3, 'E', 5, 6]
Or you can use a list comprehension to shorten the loop:
string = "1,B,C,3,E,5,6" string_list = [int(e) if e.isdigit() else e for e in string.split(",")] print(string_list)
Output:
[1, 'B', 'C', 3, 'E', 5, 6]
Conclusion
Today you learned how to convert a comma-delimited string to a list in Python.
To recap, call string.split(“,”) on the string you want to convert to a list. To avoid confusion, remember to check if the string is not empty.
Thanks for reading. I hope you find it useful!
Happy coding!