str() vs repr() in Python
Last Updated :
17 Jun, 2023
In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object.
Python str()
In the given example, we are using the str() function on a string and floating values in Python.
Python3
s = 'Hello, Geeks.'
print (str(s))
print (str(2.0/11.0))
Output:
Hello, Geeks.
0.181818181818
Python repr()
In the given example, we are using the repr() function on a string and floating values in Python.
Python3
s = 'Hello, Geeks.'
print (repr(s))
print (repr(2.0/11.0))
Output:
'Hello, Geeks.'
0.18181818181818182
str() vs repr() in Python Examples
From the above output, we can see if we print a string using the repr() function then it prints with a pair of quotes and if we calculate a value we get a more precise value than the str() function.
Python __str__() and __repr__() with a Built-In Class
In this example, we are creating a DateTime object of the current time and we are printing it into two different formats.
str() displays today's date in a way that the user can understand the date and time. repr() prints an “official" representation of a date-time object (means using the “official” string representation we can reconstruct the object).
Python3
import datetime
today = datetime.datetime.now()
# Prints readable format for date-time object
print(str(today))
# prints the official format of date-time object
print(repr(today))
Output :
2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)
How to make them work for our own defined classes?
A user-defined class should also have a __repr__() if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__() function. In this example, We have created a class Complex which has two instance variables real and imag. We are creating custom __repr__() and __str__() methods in the class.
Python3
# Python program to demonstrate writing of __repr__ and
# __str__ for user defined classes
# A user defined class to represent Complex numbers
class Complex:
# Constructor
def __init__(self, real, imag):
self.real = real
self.imag = imag
# For call to repr(). Prints object's information
def __repr__(self):
return 'Rational(%s, %s)' % (self.real, self.imag)
# For call to str(). Prints readable form
def __str__(self):
return '%s + i%s' % (self.real, self.imag)
# Driver program to test above
t = Complex(10, 20)
# Same as "print t"
print (str(t))
print (repr(t))
Output :
10 + i20
Rational(10, 20)
Difference between Python str() and Python repr()
Points
| str()
| repr()
|
Return Value
| Returns a human-readable string representation of the object
| Returns an unambiguous string representation of the object
|
Usage
| Used for creating user-friendly output and for displaying the object as a string
| Used for debugging and development purposes to get the complete information of an object
|
Examples
| str(123) returns '123'
| repr(123) returns '123'
|
| str('hello') returns 'hello'
| repr('hello') returns "'hello'"
|
| str([1, 2, 3]) returns '[1, 2, 3]'
| repr([1, 2, 3]) returns '[1, 2, 3]'
|
| str({'name': 'John', 'age': 30}) returns "{'name': 'John', 'age': 30}"
| repr({'name': 'John', 'age': 30}) returns "{'name': 'John', 'age': 30}"
|
Similar Reads
Recursion in Python Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python | re.search() vs re.match() When working with regular expressions (regex) in Python, re.search() and re.match() are two commonly used methods for pattern matching. Both are part of the re module but function differently. The key difference is that re.match() checks for a match only at the beginning of the string, while re.sear
3 min read
Python str() function The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Letâs take a simple example to converting an Intege
3 min read
Python List Reverse() The reverse() method is an inbuilt method in Python that reverses the order of elements in a list. This method modifies the original list and does not return a new list, which makes it an efficient way to perform the reversal without unnecessary memory uses.Let's see an example to reverse a list usi
2 min read
range() vs xrange() in Python The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
4 min read
reflection in Python Reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to a function. For example, if we write type(obj) then Python will return an object which represents the type of obj. Using reflection, we can write one recursive reverse funct
3 min read
__rmul__ in Python For every operator sign, there is an underlying mechanism. This underlying mechanism is a special method that will be called during the operator action. This special method is called magical method. For every arithmetic calculation like +, -, *, /, we require 2 operands to carry out operator functio
4 min read
Python vs Cpython Python is a high-level, interpreted programming language favored for its readability and versatility. It's widely used in web development, data science, machine learning, scripting, and more. However, Cpython is the default and most widely used implementation of the Python language. It's written in
4 min read
Convert Set to String in Python Converting a set to a string in Python means changing a group of unique items into a text format that can be easily read and used. Since sets do not have a fixed order, the output may look different each time. For example, a set {1, 2, 3} can be turned into the string "{1, 2, 3}" or into "{3, 1, 2}"
2 min read
Python __init__ vs __new__ In Python, __init__ and __new__ are part of a group of special methods in Python commonly referred to as dunder methods or magic methods. The term "dunder" is short for "double underscore," reflecting the naming convention with double underscores at the beginning and end of the method names.Python _
3 min read