
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between str and repr in Python
The built-in functions repr() and str() respectively call object.__repr__(self) and object.__str__(self) methods. First function computes official representation of the object, while second returns informal representation of the object.
Result of both functions is same for integer object.
>>> x = 1 >>> repr(x) '1' >>> str(x) '1'
However, it is not the case for string object.
>>> x = "Hello" >>> repr(x) "'Hello'" >>> str(x) 'Hello'
Return value of repr() of a string object can be evaluated by eval() function and results in valid string object. However, result of str() can not be evaluated.
>>> y1 = repr(x) >>> eval(y1) 'Hello' >>> y2 = str(x) >>> eval(y2) NameError: name 'Hello' is not defined
To summarize. repr() returns a default and unambiguous representation of the object, where as str() gives an informal representation that may be readable but may not be always unambiguous.
Advertisements