How to convert a string with comma-delimited items to a list in Python?

Clinteney Hui picture Clinteney Hui · Mar 22, 2011 · Viewed 609.3k times · Source

How do you convert a string into a list?

Say the string is like text = "a,b,c". After the conversion, text == ['a', 'b', 'c'] and hopefully text[0] == 'a', text[1] == 'b'?

Answer

Cameron picture Cameron · Mar 22, 2011

Like this:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]

Alternatively, you can use eval() if you trust the string to be safe:

>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')