Python repr() Function
repr() is a built-in function in Python used to get the printable representation of an object.
repr() Returns the official string representation of an object, which can usually be used to recreate the object. It differs from str() in thatrepr() focuses more on debugging and development, while str() focuses on being user-friendly.
Word meaning: repr Is representationis short for (representation).
Basic syntax and parameters
Syntax format
repr(object)
Parameter Description
- Parameter object:
- Type: any object
- Description: the object whose string representation is wanted.
Function description
- Return Value: Returns a string, usually one that can represent the object.
- Special method: An object can customize the return value by defining the
__repr__method.
Example
Example 1: repr() vs str()
Example
Difference with strings
s
=
"hello"
(
f
"str: '{str(s)}'"
)
Output: str: 'hello'
(
f
"repr: '{repr(s)}'"
)
Output: repr: 'hello'
Difference with dates and times
from
datetime
import
datetime
dt
=
datetime
.
now
(
)
(
f
"str: {str(dt)}"
)
(
f
"repr: {repr(dt)}"
)
Difference with custom classes
class
Person:
def
init
(
self
,
name
)
:
self
.
name
=
name
def
str
(
self
)
:
return
f
"Person: {self.name}"
def
repr
(
self
)
:
return
f
"Person(name='{self.name}')"
p
=
Person
(
"Tom"
)
(
f
"str: {str(p)}"
)
(
f
"repr: {repr(p)}"
)
Expected output:
str: 'hello'
repr: 'hello'
str: 2024-01-15 10:30:45.123456
repr: datetime.datetime(2024, 1, 15, 10, 30, 45, 123456)
str: Person: Tom
repr: Person(name='Tom')
Code analysis:
- For simple strings, the two results are the same.
- For dates and times,
repr()returns an expression that can rebuild the object. - Custom classes can define
__str__and__repr__method.
Example 2: debugging with repr()
Example
Show hidden characters
s
=
"hello\nworld"
(
f
"str: {str(s)}"
)
(
f
"repr: {repr(s)}"
)
Show quotation marks
text
=
"She said 'hello'"
(
f
"str: {str(text)}"
)
(
f
"repr: {repr(text)}"
)
In an interactive environment
Typing a variable name directly calls repr()
Expected output:
str: hello
world
repr: 'hello\nworld'
str: She said 'hello'
repr: "She said 'hello'"
repr() It can display hidden characters (such as newlines) and quotation marks, which makes debugging easier.
Python3 built-in function