Python | repr method
repr(obj) method returns a printable representation of an object as a string.
The printable representation of a string has a
'' wrapped around it:
x = "hello"print(repr(x))'hello'
repr(obj) method comes in handy when you need to escape special characters such as the new line character (
x = "\nhello\n"print(repr(x))'\nhello\n'
This is contrast to printing the string directly:
x = "\nhello\n"print(x)hello
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 = namedef __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'