near_me
Linear Algebra
keyboard_arrow_down 54 guides
chevron_leftDocumentation
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
check_circle
Mark as learned thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Python | repr method
schedule Aug 11, 2023
Last updated local_offer
Tags Python
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
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'
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
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!