5

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GCien
  • 2,221
  • 6
  • 30
  • 56
  • 2
    That looks like a list, not a string... – sacuL Apr 25 '18 at 13:29
  • 7
    Possible duplicate of [How to convert a string to a list in Python?](https://stackoverflow.com/questions/5387208/how-to-convert-a-string-to-a-list-in-python) – code11 Apr 25 '18 at 13:30
  • are you talking about the element inside of this list ? – Ankush Rathi Apr 25 '18 at 13:30
  • That looks like it's a duplicate question – I am sure I've seen at least several variants. Anyway, what did you try & why did it not work? – Jongware Apr 25 '18 at 13:31
  • 3
    `ast.literal_eval()` or `json.loads()` ... – zwer Apr 25 '18 at 13:31
  • Im guessing he wants "".join(str_list), and has a very weird way of writing a question. – Rohi Apr 25 '18 at 13:32
  • Making a variable by Copy/paste of your 'following string' definitely does not return a class of str when you run type(). At least on my machine. – dfundako Apr 25 '18 at 13:35
  • Wow - -10 XD yes, it's definitely a string. I promise. type(my_variable) gives ``. I missed off the bracing '. – GCien Apr 25 '18 at 13:38
  • *It's come from passing an array via AJAX post request. – GCien Apr 25 '18 at 13:40
  • Got it - just updated my question. Apologies for asking such a weird question! :) – GCien Apr 25 '18 at 14:04
  • Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Georgy Dec 13 '19 at 14:10

4 Answers4

22

You can do this

import ast

list = '["Foo","Bar","Baz","Woo"]'
list = ast.literal_eval(list)
print list
Lex Bryan
  • 750
  • 1
  • 9
  • 18
  • 2
    @GCien This should be marked as the correct answer. – drakorg Aug 05 '20 at 02:47
  • That seems the way to go to [get the *Life boat* badge](https://stackoverflow.com/help/badges/8842/lifeboat?page=1): Add an answer without any explanation [whatsoever](https://stackoverflow.com/help/promotion). – Peter Mortensen Jan 25 '23 at 17:21
7

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hadij
  • 3,661
  • 5
  • 26
  • 48
  • 2
    It looks like this can be dangerous if the data is untrusted since it can execute code, I read it is recommended to use `ast.literal_eval` instead: https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – baptx Jul 02 '21 at 14:17
  • 1
    Though this answer is about Python (about which, I admit, know nothing), not about PHP, but even so... I still believe that this statement is true even for Python: "_Rasmus Lerdorf, the creator of PHP, once wrote that »if eval() is the answer, you're almost certainly asking the wrong question«_"! – trejder May 21 '23 at 21:11
4

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
txicos
  • 249
  • 3
  • 6
  • 1
    First option ruins your data if any of the elements contain a [ or ] as part of its own text. Second and third options do not start from a string and have nothing to do to string to array or list conversion. – drakorg Aug 05 '20 at 02:43
2

You can also do this:

import json

json.loads('["Foo", "Bar", "Baz", "Woo"]')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel Adu
  • 21
  • 1