str et 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__Est appelé
print('{0}'.format(p)) # __str__Est appelé
print('{0!s}'.format(p)) # __str__Est appelé

Résultat de l'exécution:

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 et repr
str et unicode
Python2 str / unicode et encoder / décoder
À propos de _ et __