Syntax
object.__str__(self)
The Python __str__
method returns a string representation of the object on which it is called. For example, if you call print(x)
an object x
, Python internally calls x.__str__()
to determine the string representation of object x
. This method is also used to implement the built-in str()
function.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
Background str()
Python’s built-in str(x)
function converts the object x
to a string using the x.__str__()
method or, if non-existent, the repr(x)
built-in function to obtain the string conversion.
>>> str(42) '42' >>> str(3.14) '3.14' # Equivalence of str() and __str__() on lists: >>> str([1, 2, 3]) '[1, 2, 3]' >>> [1, 2, 3].__str__() '[1, 2, 3]' # Dictionary: >>> str({'Donna': 33, 'Harvey': 44}) "{'Donna': 33, 'Harvey': 44}"
Example Custom __str__()
In the following example, you create a custom class Data
and overwrite the __str__()
method so that it returns a dummy string.
class Data: def __str__(self): return '... my result of str ...' a = Data() print(str(a)) # ... my result of str ...
If you hadn’t defined the __str__()
method, Python would’ve used the default implementation:
Default __str__() Implementation
Per default, any object has a __str__()
method implementation—so you can represent any object x
as a string explicitly by using the built-in str(x)
function or using it implicitly by calling print(x)
.
However, the default __str__() implementation provides only meta information about the object. For example, on our custom object, it provides the string representation <__main__.Data object at 0x0000028A54B0AFA0>
. This includes the following information:
- The location where the object is defined (e.g.,
__main__
). - The name of the object (e.g.,
Data
). - The memory location of the object as a hexadecimal number (e.g.,
0x0000028A54B0AFA0
).
Here’s an example:
class Data: pass a = Data() print(str(a)) # <__main__.Data object at 0x0000028A54B0AFA0>
__repr__ vs __str__
The difference between __str__()
and __repr__()
methods is that __str__()
is expected to return a human-readable format, whereas __repr__()
is expected to return a formal string representation of the object that should be sufficient to reconstruct the object (e.g., including object state variables).
Here’s an example:
import datetime now = datetime.datetime.now() print(now.__str__()) # 2021-12-06 11:14:56.285055 print(now.__repr__()) # datetime.datetime(2021, 12, 6, 11, 14, 56, 285055)
💡 The first output is a human-readable format, whereas the second output could be use to reconstruct the original object, e.g., by passing the output string into the eval()
function.
However, the methods are closely related and they can even call each other if one of them is not implemented:
Python uses the __str__()
method as a priority when being forced to convert an object to a string. If __str__()
is not defined, it attempts to call __repr__()
. Only if this is not defined as well, it uses the default string representation of any object with the memory address and the name and location of the object’s class definition.
Here’s what happens if you define __repr__
but not __str__
:
class Data: def __repr__(self): return 'finxter' a = Data() print(str(a)) # finxter
And here’s what happens if both methods are defined __str__()
and __repr__()
—Python prioritizes the definition of the __str__()
method:
class Data: def __repr__(self): return 'finxter' def __str__(self): return 'python' a = Data() print(a) # python
The __str__()
method has some more powerful arguments—you can learn about them in our detailed blog tutorial here.
References:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.