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}” |
str() vs repr() in Python
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.