How to convert comma-delimited string to list in Python? How to convert comma-delimited string to list in Python? python python

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


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']


In the case of integers that are included at the string, if you want to avoid casting them to int individually you can do:

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

It is called list comprehension, and it is based on set builder notation.

ex:

>>> mStr = "1,A,B,3,4">>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]>>> mList>>> [1,'A','B',3,4]


Consider the following in order to handle the case of an empty string:

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