Table of Contents
Issue
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"]'
This is definitely a string representation as well. type()
gave:
<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”.
Solution
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
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')
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']
Answered By – txicos
Answer Checked By – Gilberto Lyons (BugsFixing Admin)