LoginSignup
0
1

More than 3 years have passed since last update.

strとrepr

Last updated at Posted at 2020-06-20
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__が呼び出される
print('{0}'.format(p)) # __str__が呼び出される
print('{0!s}'.format(p)) # __str__が呼び出される

実行結果:

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)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1