[PYTHON] str and repr

import datetime

print('s')
print(str('s'))
print(repr('s'))

d = datetime.datetime.now()
print(d)
print(str(d))
print(repr(d))

print('{!r}'.format('test')) #repr
print('{}'.format('test1'))
print('{!s}'.format('test2')) #str


class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Point<object>'

    def __str__(self):
        return 'point ({}, {})'.format(self.x, self.y)


p = Point(10, 20)
print('{0!r}'.format(p)) # __repr__Is called
print('{0}'.format(p)) # __str__Is called
print('{0!s}'.format(p)) # __str__Is called

Execution result:

s
s
's'
2020-06-21 08:42:07.565478
2020-06-21 08:42:07.565478
datetime.datetime(2020, 6, 21, 8, 42, 7, 565478)
'test'
test1
test2
Point<object>
point (10, 20)
point (10, 20)

Recommended Posts

str and repr
str and unicode
Python2 str / unicode and encode / decode
About _ and __