- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an object x to an expression string in Python?
The str function converts an object in python to a string representation. There is another function called repr() in python that converts object to an expression string. __repr__'s goal is to be unambigous while __str__'s is to be readable. __repr__ is used to compute the “official” string representation of an object.
Example
Let's take an example of datetime to understand what these 2 produce.
import datetime today = datetime.datetime.now() str(today) repr(today)
Output
This will give the output
'2018-04-08 11:25:36.918979' 'datetime.datetime(2018, 4, 8, 11, 25, 36, 918979)'
As you can see from the output, str gives a pretty, formatted result. Repr just throws an object constructor representation at us for the given object.
Advertisements