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?

2
  • 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. Commented May 10, 2016 at 9: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. Commented May 10, 2016 at 11:04

2 Answers 2

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']")
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.