5/17/2020

Python - str() vs repr()

** str() vs repr()


==========================================

# The goal of __repr__ is to be unambiguous
# The goal of __str__ is to be readable

==========================================

==========================================

a = [1, 2, 3, 4]
b = 'sample string'

print(str(a))
print(repr(a))

print(str(b))
print(repr(b))

---------------------------------

[1, 2, 3, 4]
[1, 2, 3, 4]
sample string
'sample string'

---------------------------------

==========================================

import datetime
import pytz

a = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)

b = str(a)

print('str(a): {}'.format(str(a)))
print('str(b): {}'.format(str(b)))

print()

print('repr(a): {}'.format(repr(a)))
print('repr(b): {}'.format(repr(b)))

print()

---------------------------------

str(a): 2020-05-17 01:18:15.230995+00:00
str(b): 2020-05-17 01:18:15.230995+00:00

repr(a): datetime.datetime(2020, 5, 17, 1, 18, 15, 230995, tzinfo=)
repr(b): '2020-05-17 01:18:15.230995+00:00'

---------------------------------