How to Print an Object as a String in Python?

Estimated read time 2 min read

In Python, you can print an object as a string by defining a special method called __str__() for that object’s class. This method returns a string representation of the object that can be printed using the print() function.

Here is an example:

class Person:
    def __init__(self, name, age): = name
        self.age = age

    def __str__(self):
        return f"Person(name='{}', age={self.age})"

person = Person('Alice', 25)

In this example, we define a Person class with a __str__() method. This method returns a string representation of the Person object that includes the person’s name and age. The __str__() method is automatically called when the object is printed using the print() function.

We create a Person object called person with the name “Alice” and the age 25. When we print the person object using the print() function, Python calls the __str__() method to convert the object to a string. The output of this code will be:

Person(name='Alice', age=25)

Note that the string returned by the __str__() method should be a valid Python expression that can be used to recreate the object. In this example, the string returned by __str__() includes the object’s class name and constructor arguments, so the string can be used to create a new Person object using eval() or other Python functions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply