close
The Wayback Machine - https://web.archive.org/web/20241010041551/https://www.geeksforgeeks.org/str-vs-repr-in-python/
Open In App

str() vs repr() in Python

Last Updated : 17 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

How to Fix "TypeError: can only concatenate str (not 'NoneType') to str" in Python
In Python, strings are a fundamental data type used to represent text. One common operation performed on the strings is concatenation which involves the joining of two or more strings together. However, this operation can sometimes lead to errors if not handled properly. One such error is the TypeError: can only concatenate str to the str. This art
4 min read
Python repr() Function
Python repr() Function returns a printable representation of an object in Python. In other words, we can say that the Python repr() function returns a printable representation of the object by converting that object to a string. Example In the code, repr(s) returns the string 'Hello, Geeks.' enclosed in single quotes. repr(2.0/11.0) calculates the
4 min read
Difference between str.capitalize() VS str.title()
Both title() and capitalize() have similar functionality of capitalizing first characters. Let us see the difference between the two of them. Method 1: title() title() function in Python is the Python String Method which is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the string and retu
3 min read
Python | Pandas str.join() to join string/list elements with passed delimiter
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.join() method is used to join all elements in list present in a series with passed delimiter. Since strings are also array of
2 min read
Python | Pandas Series.str.cat() to concatenate string
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.cat() is used to concatenate strings to the passed caller series of string. Distinct values from a different series can be pas
3 min read
Python | Pandas Series.str.wrap()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.wrap() is an important method when dealing with long text data (Paragraphs or messages). This is used to distribute long text
2 min read
Python | Pandas Series.str.count()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.count() method is used to count occurrence of a string or regex pattern in each string of a series. Additional flags argument
3 min read
Python | Pandas Series.str.startswith()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas startswith() is yet another method to search and filter text data in Series or Data Frame. This method is Similar to Python's sta
3 min read
Python | Pandas Series.str.endswith()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas endswith() is yet another method to search and filter text data in a Series or a Data Frame. This method is Similar to Python's e
3 min read
Python | Pandas Series.str.lower(), upper() and title()
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. Python has some inbuilt methods to convert a string into a lower, upper, or Camel case. But these methods don't work on lists and other multi-st
4 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Pandas Series.str.pad()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to add padding (whitespaces or other characters) to every string element in a series. .str has to be prefixed ev
4 min read
Python | Pandas Series.str.swapcase()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to swap case of each string in a series. This means lower case characters will be converted into uppercase and U
3 min read
Python | Pandas series.str.get()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.get() method is used to get element at the passed position. This method works for string, numeric values and even lists throu
3 min read
Python | Pandas Series.str.partition()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.partition() works in a similar way like str.split(). Instead of splitting the string at every occurrence of separator/delimit
3 min read
Python | Pandas Series.str.strip(), lstrip() and rstrip()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas provide 3 methods to handle white spaces(including New lines) in any text data. As can be seen in the name, str.lstrip() is used
4 min read
Python | Pandas Series.str.repeat()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.repeat() method is used to repeat string values in the same position of passed series itself. An array can also be passed in c
3 min read
Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a method to split string around a passed separator or delimiter. After that, the string can be stored as a list in a seri
3 min read
Python | Pandas Series.str.get_dummies()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.get_dummies() is used to separate each string in the caller series at the passed separator. A data frame is returned with all
3 min read
Python | Pandas Series.str.ljust() and rjust()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas .ljust() and .rjust() are Text methods used to deal with text data in series. Since these methods are applicable only on strings,
3 min read
Python | Pandas Series.str.zfill()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas zfill() method is used to fill left side of string with zeros. If length of string is more than or equal to the width parameter,
2 min read
Python | Pandas Series.str.slice_replace()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.slice_replace() method is used to replace a slice string present in Pandas series object. Since this is a pandas string metho
2 min read
Python | Pandas Series.str.slice()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.slice() method is used to slice substrings from a string present in Pandas series object. It is very similar to Python's basi
3 min read
Python | Pandas Series.str.find()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.find() method is used to search a substring in each string present in a series. If the string is found, it returns the lowest
3 min read
Python | Pandas Series.str.rfind()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas str.rfind() method is used to search a substring in each string present in a series from the Right side. If the string is found, i
3 min read
Python | Pandas Series.str.isdigit()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.isdigit() method is used to check if all characters in each string in series are digits. Whitespace or any other character oc
2 min read
Python | Pandas Series.str.rpartition()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.rpartition() works in a similar way like str.partition() and str.split(). Instead of splitting string on every occurrence fro
3 min read
Python | Pandas Series.str.findall()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.findall() method is also used to find substrings or separators in each string in a series. But it is different from str.find(
2 min read
Python | Pandas Series.str.len()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.len() method is used to determine length of each string in a Pandas series. This method is only for series of strings. Since
3 min read
Python | Pandas Series.str.isdecimal()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas isdecimal() is used to check whether all characters in a string are decimal. This method works in a similar way to str.isdigit()
2 min read
Article Tags :
Practice Tags :