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?
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']")
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.
evalorexecif 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.namedtupleusesexecto build its classes. However, it does establish that it's arguments are valid identifiers and so theexecwill work only as expected.