search

What is the use of the "str" and "repr" methods in Python?

The **str** and **repr** methods in Python are used to represent objects of a class as human-readable strings.

The **str** method returns a string representation of the object, which is intended to be human-readable and can be used for display purposes. If an object does not have a **str** method defined, Python will call the built-in **str()** function on the object, which returns a string that represents the object as a code string (i.e., **"<__main__.ClassName object at 0x7f7c8cb8a668>"**).

The **repr** method returns a string representation of the object, which is intended to be unambiguous and should be used for debugging and development purposes. If an object does not have a **repr** method defined, Python will call the built-in **repr()** function on the object, which returns a string that represents the object as a Python expression that can be used to recreate the object (i.e., **"ClassName(arg1=value1, arg2=value2)"**).

Related Questions You Might Be Interested