Python – convert a string to an array

Question:

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

I 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".

Asked By: GCien

||

Answers:

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 the Python array module, then you could do like this:

import array as ar

x = ar.array('c')  # Character 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

You can do this

import ast

list = '["Foo","Bar","Baz","Woo"]'
list = ast.literal_eval(list)
print list
Answered By: Lex Bryan

No-package solution

You can use the eval function:

list = eval('["Foo", "Bar", "Baz", "Woo"]')
print (list)

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

Alternative solution

Based on baptx’s comment, an alternative way (probably a better one) is to use the ast package:

from ast import literal_eval

list = literal_eval('["Foo", "Bar", "Baz", "Woo"]')
print (list)

# ['Foo', 'Bar', 'Baz', 'Woo']
Answered By: Hadij

You can also do this:

import json

json.loads('["Foo", "Bar", "Baz", "Woo"]')
Answered By: Daniel Adu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.