I have input() in which must be typed something like this:
[[('Zamek', 2), ('Polonez', 7), ('Wojska Polskiego', 12), ('Słowiańska', 17), ('Solidarności', 21)], [('Zamek', 10), ('Polonez', 15), ('Wojska Polskiego', 21), ('Słowiańska', 24), ('Solidarności', 28)], [('Zamek', 17), ('Polonez', 22), ('Wojska Polskiego', 29), ('Słowiańska', 32), ('Solidarności', 36)], [('Zamek', 22), ('Polonez', 30), ('Wojska Polskiego', 37), ('Słowiańska', 40), ('Solidarności', 45)]]
and input() convert it to string, but then I can't work on this list. What I need to do to convert input?
2 Answers 2
Dangerous version:
data = input("Enter your list: ")
parsed_data = eval(data)
answered Jun 27, 2017 at 7:17
zwer
25.9k3 gold badges53 silver badges70 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If you know the input is safe (only you provide it), you can just use eval
l = eval(input("bring it on:"))
a better version is ast.literal_eval
l = ast.literal_eval(input("much safer:"))
still in both cases you need to be sure the input is not getting from an un-trusted source
If you can make your input to be a json you have an even safer/better solution:
#possible input: [[["Zamek", 2], ["Polonez", 7], ["Wojska Polskiego", 12], ["S\\u0142owia\\u0144ska", 17], ["Solidarno\\u015bci", 21]], [["Zamek", 10], ["Polonez", 15], ["Wojska Polskiego", 21], ["S\\u0142owia\\u0144ska", 24], ["Solidarno\\u015bci", 28]], [["Zamek", 17], ["Polonez", 22], ["Wojska Polskiego", 29], ["S\\u0142owia\\u0144ska", 32], ["Solidarno\\u015bci", 36]], [["Zamek", 22], ["Polonez", 30], ["Wojska Polskiego", 37], ["S\\u0142owia\\u0144ska", 40], ["Solidarno\\u015bci", 45]]]
l = json.loads(input("please provide it in json format..."))
answered Jun 27, 2017 at 7:17
Yoav Glazner
8,0511 gold badge22 silver badges36 bronze badges
Comments
lang-py