GCien
GCien

Reputation: 2349

Python - convert a string to an array

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

Upvotes: 5

Views: 69249

Answers (4)

Hadij
Hadij

Reputation: 4600

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

Upvotes: 7

Daniel Adu
Daniel Adu

Reputation: 21

You can also do this:

import json

json.loads('["Foo", "Bar", "Baz", "Woo"]')

Upvotes: 2

txicos
txicos

Reputation: 289

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

Upvotes: 4

Lex Bryan
Lex Bryan

Reputation: 760

You can do this

import ast

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

Upvotes: 22

Related Questions