__str__()

The __str__() dunder method returns a reader-friendly string representation of a class object. It can be called with the built-in str() and print() functions. Unlike __repr__(), it is not necessary that __str__() return a valid Python expression.

Syntax

class ClassName:
  def __str__(self):

The __str__() method accepts no parameters. self is an implicit reference to the instance of ClassName.

Codebyte Example

The example below showcases various ways the __str__() can be called using an object literal, the built-in str() function, and the __str__() dunder method. All return the same string output; the aim is to make the output readable:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy

Contributors