repr()andstr()are two built-in functions in Python for converting objects to strings, and there are some key differences between them:
-
Different purposes:
repr(): Returns a string that should be a valid Python expression and can be used to recreate the object (if possible). It is mainly used for development and debugging, aiming to provide as much information as possible.str(): Returns a string that is in a human-readable form, mainly used for displaying objects.
-
Implementation method:
repr(): Usually by the object's__repr__()method implementation.str(): Usually by the object's__str__()method implementation. If the object does not define__str__()method, it will use__repr__()method as a substitute.
-
Application scenarios:
repr(): Used when you need to view the "official" string representation of an object, for example during debugging or logging.str(): Used when you need to convert an object into a human-readable form, for example when printing or displaying.
-
Output format:
repr(): The output string is usually more detailed and can be used to accurately reconstruct the object.str(): The output string is usually more concise and human-friendly.
For example, let's look at how a custom object implements__repr__()and__str__()methods:
Example
class MyClass:
def __repr__(self):
return "MyClass(param1='value1', param2='value2')"
def __str__(self):
return "MyClass with value1 and value2"
obj = MyClass()
print(repr(obj)) # Output: MyClass(param1='value1', param2='value2')
print(str(obj)) # Output: MyClass with value1 and value2
def __repr__(self):
return "MyClass(param1='value1', param2='value2')"
def __str__(self):
return "MyClass with value1 and value2"
obj = MyClass()
print(repr(obj)) # Output: MyClass(param1='value1', param2='value2')
print(str(obj)) # Output: MyClass with value1 and value2
In this example,repr(obj)provides a detailed string representation, containing the object's parameter information, whilestr(obj)provides a concise, human-readable string representation.