[python] str과 repr 비교

python 2018. 1. 23. 14:57


python에는 Java의 toString()과 같은 문법이 있다. 




>>> import datetime

>>> today = datetime.datetime.now()

>>> str(today)

'2018-01-23 14:49:37.284361'

>>> repr(today)




>>> f=1.1111111111111111

>>> str(f)

'1.11111111111'

>>> repr(f)

'1.1111111111111112'




str은 사용자가 보기 편하게 "비공식"적으로 쓰는 문자열(반드시) 표현법이고,

repr은 시스템에서 구분하기 위한 공식적연 표현법이며 문자열이 아니어도 된다.



https://docs.python.org/3.7/reference/datamodel.html#object.__repr__


object.__repr__(self)

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.


This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.


object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.


This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.


The default implementation defined by the built-in type object calls object.__repr__().



Posted by '김용환'
,