In this tutorial, we will learn how to convert a string to an object in Python. Converting a string to an object is useful when you want to evaluate a string as if it’s a variable or a function name.
For instance, in a configuration file, you might come across a string representation of a class or function name, and you’ll want to call this class or function directly in your code.
Step 1: Import the necessary modules
The first step is to import the required module, which is ast (Abstract Syntax Trees). This module helps us convert a string to various Python objects, like list, dictionary, and tuple.
1 |
import ast |
Step 2: Define a string to be converted
For this tutorial, let’s assume we have a string that represents a list, dictionary, and tuple.
1 2 3 |
string_list = "[1, 2, 3, 4, 5]" string_dict = "{'a': 1, 'b': 2, 'c': 3}" string_tuple = "(1, 2, 3)" |
Step 3: Convert the string to an object
To convert the strings to appropriate objects, we need to use the ast.literal_eval() function from the ast module.
1 2 3 |
object_list = ast.literal_eval(string_list) object_dict = ast.literal_eval(string_dict) object_tuple = ast.literal_eval(string_tuple) |
Step 4: Print the result
Now that we have successfully converted our strings into objects, let’s print the results.
1 2 3 |
print(f"List Object: {object_list}") print(f"Dictionary Object: {object_dict}") print(f"Tuple Object: {object_tuple}") |
After executing the above code, the output should be as follows:
List Object: [1, 2, 3, 4, 5] Dictionary Object: {'a': 1, 'b': 2, 'c': 3} Tuple Object: (1, 2, 3)
Full Code
Here is the full code for this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import ast string_list = "[1, 2, 3, 4, 5]" string_dict = "{'a': 1, 'b': 2, 'c': 3}" string_tuple = "(1, 2, 3)" object_list = ast.literal_eval(string_list) object_dict = ast.literal_eval(string_dict) object_tuple = ast.literal_eval(string_tuple) print(f"List Object: {object_list}") print(f"Dictionary Object: {object_dict}") print(f"Tuple Object: {object_tuple}") |
Conclusion
In this tutorial, we have learned how to convert a string to an object in Python using the ast.literal_eval() function. This is particularly useful in several scenarios, such as parsing configuration files or converting data received in string formats. The ast module allows us to safely evaluate strings into Python objects without the security risks associated with using the eval()
function.