2

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

1

Dangerous version:

data = input("Enter your list: ")
parsed_data = eval(data)
Sign up to request clarification or add additional context in comments.

Comments

1

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..."))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.