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]