[python]python中str()与repr()的区别与联系

#原帖地址: https://blog.csdn.net/ysgjiangsu/article/details/75299883

搜了好些博文,说了有一堆废话,也没几个讲清楚python中str()与repr()的区别与联系,于是写此文。

首先,上英文原文

The str() function is meant to return representations of values which are fairly human-readable,while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax).

#

For objects which don’t have a particular representation for human consumption, str() will return the same value as repr().

Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function.

Strings and floating point numbers, in particular, have two distinct representations.

简言之,str()便于程序员理解,repr()便于interpreter理解(大多数博文也这么说) 
‘################################################## 
两者异同: 
同:对于数值、列表、字典等类型,二者具有完全相同的输出。以上类型的共同特征是:与人们理解的意思没有特别不同的表达(也就是说当程序员能理解,interpreter也能理解的时候,二者具有相同输出)

异:对于字符串和浮点数,二者输出明显不同。

举个例子
>>> s = 'hello,world!'
>>> str(s)
'hello,world!'
>>> repr(s)
"'hello,world!'"
>>> s1 = 'hello,world!\n'
>>> str(s1)//字符串还是字符串,没变
'hello,world!\n'
>>> print str(s1)//输出字符串内容且有换行,符合人们理解
hello,world!

>>> repr(s1)//注意双斜杠,即多了转义符,且字符串外围又有引号
"'hello,world!\\n'"
>>> print repr(s1)//将机器看到的内容原样打印出来,无换行
'hello,world!\n'
>>> str(1000L)
'1000'
>>> repr(1000L)
'1000L'
>>> str(0.001)
'0.001'
>>> repr(0.001)
'0.001'
>>> str(0.00000001)
'1e-08'
>>> repr(0.00000001)
'1e-08'
>>> 
  • 但在Python 2.7.5中,操作浮点数的时候,二者获得相同输出,这一点与英文表述不符。可能是Python版本原因,若有知道的小伙伴,欢迎指正。

猜你喜欢

转载自blog.csdn.net/madrabbit1987/article/details/81272348