Diff btw repr() and str() in python

The repr() Function in Python

repr() is a built-in function in Python that returns a string representation of an object. This representation is often called the "official" string representation because it's intended to be unambiguous and precise, suitable for debugging or creating output that can be evaluated as Python code.

How repr() works:

* It calls the __repr__() method of the object internally.

* It returns a string that ideally includes enough information to recreate the object.

* The returned string is often enclosed in single quotes.

Key differences between repr() and str():

* str() is used for creating human-readable strings.

* repr() is used for debugging and creating strings that can be evaluated as Python code.

Example:

import datetime

x = 10

y = "Hello, world!"

z = datetime.datetime.now()

print(repr(x)) # Output: '10'

print(repr(y)) # Output: "'Hello, world!'"

print(repr(z)) # Output: "datetime.datetime(2024, 8, 13, 12, 13, 09, 912345)"

As you can see, repr() provides a more detailed and machine-readable representation of the objects compared to str().

Customizing repr() for your classes:

You can define the __repr__() method in your custom classes to control the output of repr() for your objects. This is often useful for debugging purposes.

When to use repr():

* Debugging: To inspect the contents of an object in detail.

* Logging: To create detailed log messages.

* Creating output that can be evaluated as Python code.

In summary, repr() is a valuable tool for understanding and working with Python objects, especially when precision and detail are important.