The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC L Beethoven - Piano Sonata No 8 in C

--

Chapters
00:00 Question
00:20 Accepted answer (Score 268)
00:32 Answer 2 (Score 199)
01:01 Answer 3 (Score 56)
01:17 Answer 4 (Score 29)
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/5387...

Answer 1 links:
[Cameron]: https://stackoverflow.com/users/21475/ca...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #list

#avk47



ACCEPTED ANSWER

Score 273


Like this:

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



ANSWER 2

Score 199


Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you're dealing with right now, go with @Cameron's answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'



ANSWER 3

Score 60


The following Python code will turn your string into a list of strings:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)



ANSWER 4

Score 29


I don't think you need to

In python you seldom need to convert a string to a list, because strings and lists are very similar

Changing the type

If you really have a string which should be a character array, do this:

In [1]: x = "foobar"
In [2]: list(x)
Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']

Not changing the type

Note that Strings are very much like lists in python

Strings have accessors, like lists

In [3]: x[0]
Out[3]: 'f'

Strings are iterable, like lists

In [4]: for i in range(len(x)):
...:     print x[i]
...:     
f
o
o
b
a
r

TLDR

Strings are lists. Almost.