A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://realpython.com/ref/glossary/string-representation/ below:

string representation | Python Glossary – Real Python

  1. Reference
  2. Python Glossary/
string representation

In Python, string representation refers to how objects are represented as strings. This feature is essential for debugging and logging purposes.

Python offers two primary special methods for defining string representations:

  1. .__str__() is intended to provide a nice or user-friendly string representation of an object
  2. .__repr__() aims to provide a more precise and developer-friendly string representation that can often be used to recreate the object.

When you print an object or use the built-in str() function, Python internally calls the .__str__() method. If .__str__() isn’t defined, then Python falls back to .__repr__(). Conversely, if you use the built-in repr() function or access the object in a REPL, Python calls .__repr__().

Example

Here’s an example that illustrates both string representations:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def __str__(self):
        return f"{self.make} {self.model}"

    def __repr__(self):
        cls = type(self).__name__
        return f"{cls}(make='{self.make}', model='{self.model}')"

# Usage
corolla = Car("Toyota", "Corolla")
print(str(corolla))  # Output: Toyota Corolla
print(repr(corolla)) # Output: Car(make='Toyota', model='Corolla')
Copied!

In this example, .__str__() provides a user-friendly description of the concrete Car object, while .__repr__() gives a developer-friendly representation suitable for debugging.

For additional information on related topics, take a look at the following resources:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4