将一个string转换为一个数组
如何将string转换为数组? 说这个string就像是text = "a,b,c" 。 
 在转换之后, text == ['a', 'b', 'c'] ,希望text[0] == 'a' , text[1] == 'b' ? 
谢谢
喜欢这个:
 >>> text = 'a,b,c' >>> text = text.split(',') >>> text [ 'a', 'b', 'c' ] 
 或者,如果您信任string是安全的,则可以使用eval() : 
 >>> text = 'a,b,c' >>> text = eval('[' + text + ']') 
只是为了增加现有的答案:希望你未来会遇到类似的情况:
 >>> word = 'abc' >>> L = list(word) >>> L ['a', 'b', 'c'] >>> ''.join(L) 'abc' 
但是现在你正在处理的是@ 卡梅隆的答案。
 >>> word = 'a,b,c' >>> L = word.split(',') >>> L ['a', 'b', 'c'] >>> ','.join(L) 'a,b,c' 
下面的Python代码将把你的string变成一个string列表:
 import ast teststr = "['aaa','bbb','ccc']" testarray = ast.literal_eval(teststr) 
我不认为你需要
在Python中,你很less需要将string转换为列表,因为string和列表非常相似
改变types
如果你真的有一个string应该是一个字符数组,请这样做:
 In [1]: x = "foobar" In [2]: list(x) Out[2]: ['f', 'o', 'o', 'b', 'a', 'r'] 
不改变types
请注意,string非常像Python中的列表
string有访问器,如列表
 In [3]: x[0] Out[3]: 'f' 
string是可迭代的,就像列表一样
 In [4]: for i in range(len(x)): ...: print x[i] ...: f o o b a r 
TLDR
string是列表。 几乎。
如果你真的想要数组:
 >>> 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' 
如果你不需要数组,并且只想通过索引来查看你的字符,记住一个string是一个可迭代的,就像列表一样,除非它是不可变的:
 >>> text = "a,b,c" >>> text = text.replace(',', '') >>> text[0] 'a' 
 如果你想分割空格,你可以使用.split() : 
 a='mary had a little lamb' z=a.split() print z 
输出:
 ['mary', 'had', 'a', 'little', 'lamb'] 
我通常使用:
 l = [ word.strip() for word in text.split(',') ] 
  strip去除字的空间。 
 为了转换一个forms为a="[[1, 3], [2, -6]]"的string ,我写了没有优化的代码: 
 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 
m ='[[1,2,3],[4,5,6],[7,8,9]]'
m = eval(m.split()[0])
[[1,2,3],[4,5,6],[7,8,9]]
 # to strip `,` and `.` from a string -> >>> 'a,b,c.'.translate(None, ',.') 'abc' 
 您应该使用string的内置translate方法。 
 在Python shell中键入help('abc'.translate)以获取更多信息。 
使用functionPython:
 text=filter(lambda x:x!=',',map(str,text))