ZetDude ZetDude - 8 months ago 33
Python Question

Get list from input python

I need to form a list of Strings from an input. I've tried other answers, but they only work for numbers and only when there are no spaces in it. For example:

Enter input: ["Test 1", "Test 2", "Test 3"]
["Test 1", "Test 2", "Test 3"]

or something similar. (
Enter input: "Test 1", "Test 2", etc..
could also work
Thank you (I'm a newb)


For a case like this, you want ast.literal_eval; as long as they enter a legitimate Python literal, it will work. json.loads can also work, though it's less expressive than full Python literal syntax. Either way, you'd need to verify that it actually made a list, e.g.

bad = True
while bad:
    userinput = input("Enter text:")
        userlist = ast.literal_eval(userinput)
    except Exception:
        bad = not isinstance(userlist, list)
    if bad:
        print("Not a valid Python list")
# Once you get here, you have a legal list stored in userlist