Home » Python

str() vs repr() functions in Python

Python str() and repr() methods: In this tutorial, we will learn about the str() and repr() functions, their uses and difference in Python programming language.
Submitted by Bipin Kumar, on December 02, 2019

For converting any type of data to string type in python there are multiple methods available in its built-in library. With slight different features, multiple methods can be useful for programmers. Here are two methods to convert the data type to string in python.

1) Python str() function

str() is a built-in function in Python that is used to convert any type of data into the string type. For the use of str(), there is no need to import it in the program and it returns the string representation of the value whatever passes with the str() function. For example, if we pass a float or int value in str() function then it will be a string. For a better understanding of it.

Examples:

>>> a=735  
>>> b=777.97  
>>> s1=str(a)
>>> print(s1)
735

>>> s2=str(b)
>>> print(s2)
777.97

>>> type(a) 
<class 'int'> 

>>> type(s1) 
<class 'str'>

>>> type(s2)
<class 'str'>

2) Python repr() function

repr() function is also a built-in function in Python which is slightly different from the str() function. It also returns the string representation of the value whatever passes with the function repr(). There is a slight difference between the str() and repr() function is that when we pass a string in repr() then it returns the string with the single quotation but str() simply return the actual string with no quotation marks.

Let's see some examples for a better understanding of the repr() function and the difference between the str() function.

Example:

>>> b=777.45889
>>> s2=repr(b)  
>>> print(s2)
777.45889

>>> p='Includehelp'  
>>> s1=repr(p)
>>> print(s1)
'Includehelp'  

>>> r=str(p)
>>> print(r)
Includehelp

>>> q=str(b)
>>> print(q)
777.45889

>>> type(s1)
<class 'str'>

>>> type(s2)
<class 'str'>

As from the above examples, we have seen that when we pass a string with repr() function then it returns a string with a single quotation mark but when we pass the same string with the str() function then it simply returns the actual string. This is the main difference between the str() and repr() function in Python. Else both methods do the work of conversion of type of the value to string type.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.