Python - 将字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50023635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - convert string to an array
提问by GCien
How would I convert the following string to an array with python (this string could have an indefinite number of items)?
我将如何将以下字符串转换为带有 python 的数组(此字符串可能有无限数量的项目)?
'["Foo","Bar","Baz","Woo"]'
This is definitely a string representation as well. type()
gave:
这绝对也是一个字符串表示。type()
给:
<class 'str'>
Update:
更新:
Got it.
知道了。
interestedin = request.POST.get('interestedIn')[1:-1].split(',')
interested = []
for element in interestedin:
interested.append(element[1:-1])
Where request.POST.get('interestedIn')
gave the '["Foo","Bar","Baz","Woo"]'
string list "thing".
哪里request.POST.get('interestedIn')
给出了'["Foo","Bar","Baz","Woo"]'
字符串列表“东西”。
回答by Lex Bryan
You can do this
你可以这样做
import ast
list = '["Foo","Bar","Baz","Woo"]'
list = ast.literal_eval(list)
print list
回答by txicos
Dealing with string '["Foo","Bar","Baz","Woo"]'
处理字符串 '["Foo","Bar","Baz","Woo"]'
str = '["Foo","Bar","Baz","Woo"]'
str1 = str.replace(']','').replace('[','')
l = str1.replace('"','').split(",")
print l # ['Foo', 'Bar', 'Baz', 'Woo'] A list
If you mean using python array module, then you could do like this:
如果您的意思是使用 python array module,那么您可以这样做:
import array as ar
x=ar.array('c') #char array
for i in ['Foo', 'Bar', 'Baz', 'Woo']: x.extend(ar.array('c',i))
print x #array('c', 'FooBarBazWoo')
It will be much simpler if you consider using numpy though:
不过,如果您考虑使用 numpy,它会简单得多:
import numpy as np
y=np.array(['Foo', 'Bar', 'Baz', 'Woo'])
print y # ['Foo' 'Bar' 'Baz' 'Woo']