How to convert a string to a list in Python?

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

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

回答1:

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


回答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' 


回答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) 


回答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.



回答5:

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' 


回答6:

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


回答7:

I usually use:

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

the strip remove spaces around words.



回答8:

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 


回答9:

m = '[[1,2,3],[4,5,6],[7,8,9]]'

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

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]



回答10:

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



回答11:

Using functional Python:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!