Home »
Python
str() vs repr() functions in Python
By IncludeHelp Last updated : December 15, 2024
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.
Python str() Function
The 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.
Example
a = 735
b = 777.97
s1 = str(a)
print(s1) # Output: 735
s2 = str(b)
print(s2) # Output: 777.97
print(type(a)) # <class 'int'>
print(type(s1)) # <class 'str'>
print(type(s2)) # <class 'str'>
Output
735
777.97
<class 'int'>
<class 'str'>
<class 'str'>
Python repr() Function
The 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) # Output: 777.45889
p = 'Includehelp'
s1 = repr(p)
print(s1) # Output: 'Includehelp'
r = str(p)
print(r) # Output: Includehelp
q = str(b)
print(q) # Output: 777.45889
print(type(s1)) # <class 'str'>
print(type(s2)) # <class 'str'>
Output
77.45889
'Includehelp'
Includehelp
777.45889
<class 'str'>
<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.