Is it even possible, and if it is, how could I do something like this. Imagine you run this code and type in the input ["Hello","Sup"]
list = input()
something = list[0]
Is it even possible, and if it is, how could I do something like this. Imagine you run this code and type in the input ["Hello","Sup"]
list = input()
something = list[0]
If the user is inputting a string of words separated by spaces, you can call do
something = str(list).split(" ")
This will encounter errors though if the user inputs something other than a string...
Well, you could remove "["s and "]"s and then split
it, which will return an actual list.
list.replace("[", "").replace("]", "").split()
It is pretty simple with Python.
Just use ast or json and you're fine.
import ast
string_to_be_converted = '[ "I", "am", "a", "string"]'
mylist = ast.literal_eval(string_to_be_converted)
Here, type(mylist)
shows us that mylist
is a list
, not a string
.
However, I recommend using json for such an operation. Not only it is more secure, but also way faster.
import json
string_to_be_converted = '[ "I", "am", "a", "string"]'
mylist = json.loads(string_to_be_converted)
Speed comparison:
Ast:
In [1]: %timeit ast.literal_eval(string_to_be_converted)
13.6 µs per loop
Json:
In [2]: %timeit json.loads(string_to_be_converted)
2.99 µs per loop