How To Convert String To Object In Python

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.

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.

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.

Step 4: Print the result

Now that we have successfully converted our strings into objects, let’s print the results.

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:

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.