How to Convert Comma-Delimited String to a List in Python

How to Convert Comma-Delimited String to a List in Python

To convert comma-delimited string to a list in Python, split the string with the str.split() method:

string = "A,B,C,D,E,F,G"

string_list = string.split(",")

print(string_list)

Output:

['A', 'B', 'C', 'D', 'E', 'F', 'G']

Assuming the string is not empty.

Do Not Forget to Handle Empty Strings

Using the above approach on an empty string returns a list with one empty string. But 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.

Thanks for reading. I hope you find it useful!

Happy coding!

Further Reading

List Comprehensions in Python

Python Tips and Tricks

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.