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].
-
Python has lists, not arrays.chepner– chepner2014-09-16 21:14:26 +00:00Commented Sep 16, 2014 at 21:14
-
Then why do I import "array"?Jelly– Jelly2014-09-16 21:18:39 +00:00Commented Sep 16, 2014 at 21:18
-
I have no idea. Your question does not show any indication of you doing so.chepner– chepner2014-09-16 21:30:53 +00:00Commented Sep 16, 2014 at 21:30
Add a comment
|
1 Answer
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.
4 Comments
Jelly
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?
Veedrac
@Jelly Those should be equivalent. Something else is probably wrong.
unutbu
@Jelly: What is the full traceback error message? ("Does not work" is almost never enough information for us to give help.)
Jelly
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.