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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Like this:

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

Method 2

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'

Method 3

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

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

Method 4

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.

Method 5

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

Method 6

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'

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

Method 8

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(',')]

Method 9

I usually use:

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

the strip remove spaces around words.

Method 10

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

Method 11

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:

>>> "   ttnone  two    threetttfournfivenn".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 fourtfive".split(',')
['', '', 'one', 'two', 'three', '', 'n fourtfive']

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

Method 12

# 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.

Method 13

Using functional Python:

text=filter(lambda x:x!=',',map(str,text))

Method 14

Example 1

>>> email= "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573a2e323a363e3b3e3317303a363e3b7934383a">[email protected]</a>"
>>> email.split()
#OUTPUT
["<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5a8bca0a8a4aca9aca185a2a8a4aca9eba6aaa8">[email protected]</a>"]

Example 2

>>> email= "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96fbeff3fbf7fffafff2d6f1fbf7fffab8f5f9fb">[email protected]</a>, <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aad9c5c7cfc5c4d9cfc7cbc3c6c3ceeacdc7cbc3c684c9c5c7">[email protected]</a>"
>>> email.split(',')
#OUTPUT
["<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d001408000c040104092d0a000c0401430e0200">[email protected]</a>", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4635292b23292835232b272f2a2f2206212b272f2a6825292b">[email protected]</a>"]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x