Fix Python – How to convert comma-delimited string to list in Python?

Question

Asked By – O.rka

Given a string that is a sequence of several values separated by a commma:

mStr = 'A,B,C,D,E' 

How do I convert the string to a list?

mList = ['A', 'B', 'C', 'D', 'E']

Now we will see solution for issue: How to convert comma-delimited string to list in Python?


Answer

You can use the str.split method.

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

If you want to convert it to a tuple, just

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

If you are looking to append to a list, try this:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']

This question is answered By – Matt Williamson

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0