189

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

Georgy
  • 12,464
  • 7
  • 65
  • 73
Clinteney Hui
  • 4,385
  • 5
  • 24
  • 21

14 Answers14

269

Like this:

>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]
Cameron
  • 96,106
  • 25
  • 196
  • 225
  • @Clinteney: No problem ;-) You may also want to look into [`pickle`](http://docs.python.org/library/pickle.html) if you're persisting objects to strings. – Cameron Mar 22 '11 at 05:33
  • 2
    This is not an array, it is a list, Arrays represent basic values and behave very much like lists, except the type of objects stored in them is constrained. – joaquin Mar 22 '11 at 06:32
  • 9
    Friendly reminder: Don't use eval, even if you trust the string to be safe. It's not worth the potential security hazard for anything more than personal scripts and fiddling in an interactive shell. – A. Wilson Jan 25 '13 at 20:19
  • 3
    eval('[' + text + ']') will treat a,b,c as variables, not string. – phaibin May 25 '16 at 02:30
  • 2
    Downvoted because the two proposed solutions do completely different things, and this is not explained in any way in the answer text. While the question itself is not really clear, it should be made clear in the answer that the two solutions aren't equivalent alternatives, but differing interpretations of the question. – Matteo Italia Oct 12 '17 at 06:23
  • @Cameron the solution with `eval` will never work like that. Each characters should be enclosed by "-quotes: `text = '"a","b","c"'` – cards Aug 16 '21 at 16:14
  • @cards: Yup, not sure why I even suggested `eval` in the first place, yuck. Removed entirely since this is now apparently a highly-voted answer. EDIT: Ah, because the question was edited 6 years after I answered it ;-) – Cameron Aug 18 '21 at 19:40
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'
Community
  • 1
  • 1
yurisich
  • 6,991
  • 7
  • 42
  • 63
  • 4
    Although I agree with you that @Cameron's answer was the "right now" answer I think your thoroughness makes this the more correct answer. We are rarely given comma separated strings out in the real world and it's good to know how to convert to a list regardless of format. – TristanZimmerman May 19 '17 at 18:01
58

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

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Bryan
  • 581
  • 4
  • 2
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.

firelynx
  • 30,616
  • 9
  • 91
  • 101
9

In case you want to split by spaces, you can just use .split():

a = 'mary had a little lamb'
z = a.split()
print z

Output:

['mary', 'had', 'a', 'little', 'lamb'] 
Roman Byshko
  • 8,591
  • 7
  • 35
  • 57
vivek mishra
  • 196
  • 2
  • 6
7
m = '[[1,2,3],[4,5,6],[7,8,9]]'

m= eval(m.split()[0])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Ivan
  • 34,531
  • 8
  • 55
  • 100
Josué
  • 71
  • 1
  • 1
  • 1
    Please provide some additional information along with your code so that the original poster can better understand how this solves his problem. – Ivan Jun 07 '18 at 10:23
7

If you actually want arrays:

>>> from array import array
>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> myarray = array('c', text)
>>> myarray
array('c', 'abc')
>>> myarray[0]
'a'
>>> myarray[1]
'b'

If you do not need arrays, and only want to look by index at your characters, remember a string is an iterable, just like a list except the fact that it is immutable:

>>> text = "a,b,c"
>>> text = text.replace(',', '')
>>> text[0]
'a'
Roman Byshko
  • 8,591
  • 7
  • 35
  • 57
joaquin
  • 82,968
  • 29
  • 138
  • 152
  • 1
    Out of curiosity, after you did myarray = array('c', text), where did the "c" go? since if you type array, you got array("c","abc"), but a[0]==a? Thank you – Clinteney Hui Mar 22 '11 at 12:16
  • @Clinteney: The 'c' means "create an array of characters". See [the docs](http://docs.python.org/library/array.html) for more info – Cameron Mar 22 '11 at 12:43
  • I've upvoted, but too early. I obtain **array('c', '1 1 91 0.001 228')** when calling **a = array('c',e)** where **e = "1 1 91 0.001 228"** – Valentin H Feb 24 '14 at 15:20
  • @ValentinHeinitz Yes, that is what you must get as shown in my example. What do you expect ? – joaquin Feb 24 '14 at 22:41
  • 1
    @joaquin: Ok, I got it. It's all right with the answer. I was confused by the question "text == [a,b,c]" should be "text == ['a','b','c']" – Valentin H Feb 25 '14 at 21:23
5

All answers are good, there is another way of doing, which is list comprehension, see the solution below.

u = "UUUDDD"

lst = [x for x in u]

for comma separated list do the following

u = "U,U,U,D,D,D"

lst = [x for x in u.split(',')]
Zeus
  • 6,386
  • 6
  • 54
  • 89
1

To convert a string having the form a="[[1, 3], [2, -6]]" I wrote yet not optimized code:

matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
    row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
    matrixAr.append(row)
print matrixAr
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Khalid
  • 13
  • 3
1

I usually use:

l = [ word.strip() for word in text.split(',') ]

the strip remove spaces around words.

Yannick Loiseau
  • 1,394
  • 8
  • 8
1

split() is your friend here. I will cover a few aspects of split() that are not covered by other answers.

  • If no arguments are passed to split(), it would split the string based on whitespace characters (space, tab, and newline). Leading and trailing whitespace is ignored. Also, consecutive whitespaces are treated as a single delimiter.

Example:

>>> "   \t\t\none  two    three\t\t\tfour\nfive\n\n".split()
['one', 'two', 'three', 'four', 'five']
  • When a single character delimiter is passed, split() behaves quite differently from its default behavior. In this case, leading/trailing delimiters are not ignored, repeating delimiters are not "coalesced" into one either.

Example:

>>> ",,one,two,three,,\n four\tfive".split(',')
['', '', 'one', 'two', 'three', '', '\n four\tfive']

So, if stripping of whitespaces is desired while splitting a string based on a non-whitespace delimiter, use this construct:

words = [item.strip() for item in string.split(',')]
  • When a multi-character string is passed as the delimiter, it is taken as a single delimiter and not as a character class or a set of delimiters.

Example:

>>> "one,two,three,,four".split(',,')
['one,two,three', 'four']

To coalesce multiple delimiters into one, you would need to use re.split(regex, string) approach. See the related posts below.


Related

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

Using functional Python:

text=filter(lambda x:x!=',',map(str,text))
Eratosthenes
  • 2,280
  • 1
  • 14
  • 11
0
# to strip `,` and `.` from a string ->

>>> 'a,b,c.'.translate(None, ',.')
'abc'

You should use the built-in translate method for strings.

Type help('abc'.translate) at Python shell for more info.

N 1.1
  • 12,418
  • 6
  • 43
  • 61
0

Example 1

>>> email= "myemailid@gmail.com"
>>> email.split()
#OUTPUT
["myemailid@gmail.com"]

Example 2

>>> email= "myemailid@gmail.com, someonsemailid@gmail.com"
>>> email.split(',')
#OUTPUT
["myemailid@gmail.com", "someonsemailid@gmail.com"]
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29