Every object in Python can be turned into a string: str() calls the object's __str__() method if it defines one, and falls back to __repr__() otherwise. This is exactly what print() does internally to each of its arguments, which is why print(42) and print(str(42)) produce identical output. You can customize how your own classes are displayed by overriding __str__().
1Understanding str()
Every object in Python can be turned into a string: str() calls the object's __str__() method if it defines one, and falls back to __repr__() otherwise. This is exactly what print() does internally to each of its arguments, which is why print(42) and print(str(42)) produce identical output. You can customize how your own classes are displayed by overriding __str__().
__str__() is for a readable display shown to end users; __repr__() is for an unambiguous, debugging-oriented representation shown in the REPL and inside containers like lists — define both when writing a class meant to be printed.
print(str(42))
print(str(3.14))
print(str([1, 2, 3]))2Practical Example
Here is a real-world application of str() showing how it is used in production Python code.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
print(str(Point(3, 4)))3Best Practices
Follow these guidelines when working with str():
1. Override __str__() on custom classes so printing an instance shows something meaningful instead of a default memory-address representation
2. Use f-strings instead of manual str() plus concatenation when building messages
3. Remember str(None) is the text 'None', not an empty string
Tip: __str__() is for a readable display shown to end users; __repr__() is for an unambiguous, debugging-oriented representation shown in the REPL and inside containers like lists — define both when writing a class meant to be printed.
print(str(42))
print(str(3.14))
print(str([1, 2, 3]))