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"]
Enter input: "Test 1", "Test 2", etc..
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
bad = True while bad: userinput = input("Enter text:") try: userlist = ast.literal_eval(userinput) except Exception: pass else: 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