1

I'm writing a python program that takes user input from the command line. The user is told to enter in values in a list format, i.e. the user might enter [1, 2], [2, 7], [4, 3], etc.

I'm splitting this input string at ", " so that my program has access to a list such as:

['[1, 2]', '[2, 7]', '[4, 3]']

Is there any way to convert each of these "string lists" into actual lists? I don't want to have to split these strings and remove the brackets, extract the values, and create a new list manually.

Thanks!

Danny
  • 384
  • 1
  • 5
  • 16

2 Answers2

8

Since you are asking the user for a literal Python list, you can ask Python to eval the list for you. literal_eval() only works with literals, so it's not possible to slip malicious actions into the input as you could with eval()

>>> from ast import literal_eval
>>> literal_eval('[1, 2], [2, 7], [4, 3]')
([1, 2], [2, 7], [4, 3])                           #input was a tuple

>>> list(literal_eval('[1, 2], [2, 7], [4, 3]'))
[[1, 2], [2, 7], [4, 3]]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2
import json
data = json.loads("[%s]" % user_input)

user_input is the str your user have input. in your case it is

[1, 2], [2, 7], [4, 3]

data is what you want - a list contain two item lists.

amow
  • 2,203
  • 11
  • 19
  • hm, I'm getting "ValueError: No JSON object could be decoded." – Danny Mar 19 '15 at 05:43
  • @Danny give me the user input str – amow Mar 19 '15 at 05:45
  • This would be correct if the querent was asking for json literals to be evaluated. – Tritium21 Mar 19 '15 at 05:45
  • I'm passing the user input as the *args to a function. When I print out this input within the function I get: (['[1, 2]', '[2, 7]', '[4, 3]'],) – Danny Mar 19 '15 at 05:47
  • @Danny So that another thing, your user_input string is not like the one you described in your question.Maybe your method of get the user input have some error. – amow Mar 19 '15 at 05:50
  • @Danny, why are you passing it as `*args`? Is this homework or something? – John La Rooy Mar 19 '15 at 05:51
  • No, not homework. I'm passing the input to a function that is supposed to create a text file and write blocks of text of dimensions specified by the user to the file. – Danny Mar 19 '15 at 05:54
  • @Danny you can do this by using `json.loads("[%s]" % ",".join(args))`.But this is really ugly.I dont understand why you use `*args`.Btw, John La Rooy's function is a better one to me.So I suggest you use `list(literal_eval(",".join(args)))`, do not forget the import clause – amow Mar 19 '15 at 05:55
  • So I want the user to be able to provide an arbitrary number of lists and then I want the program to draw blocks based on those lists. – Danny Mar 19 '15 at 05:55