菜鸟求大大们解释Python里str函数和repr函数的区别

菜鸟求大大们解释Python里str函数和repr函数的区别
最新回答
雨零

2022-08-07 16:27:12

我个人的理解是str主要是返回一个用户友好可读的文本,而repr则更为严谨。

简单的例子:

1
2
3
4
5
6
7
8
9
10

可以看出repr中print结果刻意保留引号来表示其为str类型,而后面一个也在精度上显示更多,对应的str方法则更注重可读性,去掉不重要的内容。

当然这个并不是一定的,有的时候如果类中__str__方法没有定义则会默认采用__str__=__repr__。


参考阅读:

  1. Different Between __str__ and __repr__:

    http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python

  2. str() vs repr() in Python 2.7.5:

    http://stackoverflow.com/questions/19331404/str-vs-repr-functions-in-python-2-7-5

>>> s = "Hello"
>>> print str(s)
Hello
>>> print repr(s)
'Hello'
>>> a = 4.0/3
>>> print str(a)
1.33333333333
>>> print repr(a)
1.3333333333333333