How to convert an object x to an expression string in Python?

PythonProgramming

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.

raja
Published on 18-Apr-2018 11:44:48
Advertisements