__str__()
Anonymous contributor
Published Jan 14, 2023
Contribute to Docs
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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours