1

I was wondering if there was a way to take a properly formatted user input array, IE '[2,1,1]' as user input, and then convert that into a int array of [2,2,1].

3
  • Python has lists, not arrays. Commented Sep 16, 2014 at 21:14
  • Then why do I import "array"? Commented Sep 16, 2014 at 21:18
  • I have no idea. Your question does not show any indication of you doing so. Commented Sep 16, 2014 at 21:30

1 Answer 1

2

You could use ast.literal_eval to safely parse a string representing a literal Python expression into a Python object:

import ast

ast.literal_eval('[2,1,1]')
# [2, 1, 1]

If the string is valid JSON, then you could instead use json. loads:

import json

json.loads('[2,1,1]')
# [2, 1, 1]

Of the two, when the string is both a literal Python expression and JSON, json.loads is faster.

Sign up to request clarification or add additional context in comments.

4 Comments

Alright, thanks for the info! ast.literal_eval(input()) works but replacing input with say s = input() ast.literal_eval(s) doesn't seem to work. What's up with that?
@Jelly Those should be equivalent. Something else is probably wrong.
@Jelly: What is the full traceback error message? ("Does not work" is almost never enough information for us to give help.)
I don't know anymore, I took out my 's' string and just used input() to get my data, then I put 's' back in to get the error for you, but now it seems to work. I must've been making a typo somwhere.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.