Python-将字符串转换为数组 [英] Python - convert string to an array

查看:99
本文介绍了Python-将字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用python将以下字符串转换为数组(该字符串可能具有不确定数量的项)?

How would I convert the following string to an array with python (this string could have an indefinite number of items)?

'["Foo","Bar","Baz","Woo"]'

这绝对也是字符串表示形式. type()给出了:

This is definitely a string representation as well. type() gave:

<class 'str'>

更新:

知道了.

interestedin = request.POST.get('interestedIn')[1:-1].split(',')

interested = []

for element in interestedin:
    interested.append(element[1:-1])

其中 request.POST.get('interestedIn')给出了'["Foo","Bar","Baz","Woo"]'字符串列出事物".

Where request.POST.get('interestedIn') gave the '["Foo","Bar","Baz","Woo"]' string list "thing".

推荐答案

处理字符串'["Foo","Bar","Baz","Woo"]'

Dealing with string '["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

如果您的意思是使用python数组模块,那么您可以这样做:

If you mean using python array module, then you could do like this:

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

如果您考虑使用numpy,它将更加简单:

It will be much simpler if you consider using numpy though:

import numpy as np
y=np.array(['Foo', 'Bar', 'Baz', 'Woo'])
print y #  ['Foo' 'Bar' 'Baz' 'Woo']

这篇关于Python-将字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆