0

The string has all the formatting of an array:

myString="['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU']"

I want to make this an array. How would I do that in python?

Theo Hodges
  • 71
  • 1
  • 2
  • 8
  • 1
    You can use the eval() function, even if it's a bit dangerous. ast.literal_eval, is better, since it won't execute functions. – Kavli May 10 '16 at 09:58
  • 1
    @Kavli Nothing wrong with using `eval` or `exec` *if the source is trusted*. For small toy projects where you're the only one entering input, it's safe to assume the source is trusted. `collections.namedtuple` uses `exec` to build its classes. However, it does establish that it's arguments are valid identifiers and so the `exec` will work only as expected. – Dunes May 10 '16 at 11:04

2 Answers2

1

You can either use literal_eval (which is safer than eval), or you can treat it as a json string:

from ast import literal_eval

li = literal_eval("['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU']")

# or with the json module

import json
li = json.loads("['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU']")
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

If this is a hobby project, you can use eval() if you want to ensure that it is in fact an array:

string = ['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU']
string = eval( string )

If you want something more secure, you can use literal_eval which won't execute functions.

Squazz
  • 3,912
  • 7
  • 38
  • 62