- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
? The ProblemTired of writing multiple lines to convert string input into a list, tuple, or dictionary in Python?
Ever wondered if there's a shortcut to parse user inputs as-is?
Let’s unlock the underrated but powerful eval() function!![]()
You're building a CLI tool or a quick script and want to allow user input like:
[1, 2, 3] # List
(4, 5, 6) # Tuple
{"name": "bhuvanesh"} # Dictionary
Using input() gives you strings — not the actual data types.
So instead of this:
data = input("Enter list: ")
# Now you need to manually parse or use json.loads()
Wouldn’t it be cool to directly get a list/tuple/dict?
user_input = input("Enter any Python literal: ")
parsed = eval(user_input)
print(type(parsed), parsed)
? Just like that, the input '[1, 2, 3]' becomes a list object.
eval() executes any code. So it's unsafe if the input comes from an untrusted source.
# Potentially dangerous
eval("__import__('os').system('rm -rf /')")
?
? Safer Alternative: ast.literal_eval
If you're dealing only with basic Python literals, use:
import ast
safe_data = ast.literal_eval(input("Enter literal: "))
print(type(safe_data), safe_data)
? Try These Examples
Input: [10, 20, 30] ➜ Output: <class 'list'> [10, 20, 30]
Input: (1, 2) ➜ Output: <class 'tuple'> (1, 2)
Input: {"id": 123} ➜ Output: <class 'dict'> {'id': 123}
Input: 'hello world' ➜ Output: <class 'str'> hello world
? Quick Summary
? Handy for quick data entry, debugging, or interactive tools
? Do you use eval() in your projects? Prefer safer methods?
Let's discuss in the comments!
?
Keep exploring these small Python features that make a big impact in productivity!