chevron_left
Documentation
Constructor floatConstructor setMethod dirMethod hasattrMethod helpMethod printMethod zipMethod mapMethod enumerateMethod reversedConstructor sliceMethod octMethod typeMethod ordMethod chrConstructor boolMethod asciiMethod anyMethod hexMethod binConstructor strConstructor intConstructor tupleMethod roundMethod nextConstructor rangeMethod inputMethod reprMethod maxMethod minMethod isinstanceConstructor listMethod divmodMethod sumMethod idMethod sortedMethod allMethod lenMethod abs
thumb_up
0
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings
Python | repr method
Programming
chevron_rightPython
chevron_rightBuilt-in Functions
chevron_rightDocumentation
schedule Jul 1, 2022
Last updated local_offer Python
Tags tocTable of Contents
expand_more Python's repr(obj)
method returns a printable representation of an object as a string.
Examples
The printable representation of a string has a ''
wrapped around it:
x = "hello"print(repr(x))
'hello'
The repr(obj)
method comes in handy when you need to escape special characters such as the new line character (\n
):
x = "\nhello\n"print(repr(x))
'\nhello\n'
This is contrast to printing the string directly:
x = "\nhello\n"print(x)
hello
Internally, the repr(obj)
function is actually calling the __repr__(self)
method of the object. We can implement this method for our own classes:
class Person:
def __init__(self, name): self.name = name
def __repr__(self): return repr("My name is " + self.name)
person_alex = Person("alex")print(repr(person_alex))
'My name is alex'
If you're using Jupyter notebook, evaluating the object directly outputs the __repr__
like so:
person_alex
'My name is alex'
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
Official Python Documentation
https://docs.python.org/3/library/functions.html#repr
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!