How To Print Object As String In Python

Python is a powerful programming language that is widely used in various domains such as web development, data science, machine learning, and more.

One of the common tasks in Python development is printing objects as strings, which can be useful in debugging or displaying information to the user. In this tutorial, we will learn how to print objects as strings in Python.

Steps:

1. Convert Object to String using str() Function

The str() function in Python converts an object to its string representation. This is the simplest method to print an object as a string. We can simply pass the object to the str() function and it will return its string representation.

The output will be:

"{'name': 'John'}"

2. Convert Object to String using repr() Function

The repr() function in Python returns a string that can be used to recreate the object. It is mostly used for debugging and generating source code. We can pass the object to the repr() function and it will return a string representation.

The output will be:

"{'name': 'John'}"

3. Implement the __str__() and __repr__() Methods

In Python, we can define the __str__() and __repr__() methods on the object to specify how it should be represented as a string. The __str__() method is called when str() is used on the object, while the __repr__() method is called when repr() is used on the object.

With the __str__() and __repr__() methods, we can now easily print the object as a string with the str() and repr() functions.

The output will be:

"John (25)"
"Person(name='John', age=25)"

Full Code:

Output:

{'name': 'John'}
{'name': 'John'}
<__main__.Person object at 0x00000221888F9E50>
<__main__.Person object at 0x00000221888F9E50>

Conclusion

Printing an object as a string in Python is a common task that can be achieved using the str() and repr() functions, or by defining the __str__() and __repr__() methods on the object.

By understanding these concepts, you can easily manipulate object data in Python programming.