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.


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

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

>>> 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.


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

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

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

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

>>> 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

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.