Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python repr() Function

Python repr() Function

Python3 Built-in Functions Python3 built-in 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

- Type: any object - Description: the object whose string representation is wanted.

Function description


Example

Example 1: repr() vs str()

Example

Difference with strings

s

=

"hello"

print

(

f

"str: '{str(s)}'"

)

   

Output: str: 'hello'

print

(

f

"repr: '{repr(s)}'"

)

 

Output: repr: 'hello'

Difference with dates and times

from

datetime

import

datetime

dt

=

datetime

.

now

(

)

print

(

f

"str: {str(dt)}"

)

print

(

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"

)

print

(

f

"str: {str(p)}"

)

print

(

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:

  1. For simple strings, the two results are the same.
  2. For dates and times,repr() returns an expression that can rebuild the object.
  3. Custom classes can define __str__ and __repr__ method.

Example 2: debugging with repr()

Example

Show hidden characters

s

=

"hello\nworld"

print

(

f

"str: {str(s)}"

)

print

(

f

"repr: {repr(s)}"

)

Show quotation marks

text

=

"She said 'hello'"

print

(

f

"str: {str(text)}"

)

print

(

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 Functions Python3 built-in function