Python内置函数——repr & str

黄舟
黄舟 原创
2017-01-19 16:45:31 968浏览

Python内置函数——repr & str

repr & str

repr(object) & str(object)

变量值被转换为字符串的两种机制:前者的目标是准确性,后者的目标是可读性
repr(object)返回一个表示对象的可打印的字符串。
这和通过转换(反引号``)处理得到的结果一致。
作为一个普通函数,可以使用这个运算有些时候是有用处的。
对于大部分类型,这个函数尝试返回一个字符串,当其传给eval(),将生成同样的对象,
(即eval(repr(object)==object.)否则生成一个用尖括号括起来的字符串,
包含着对象类型名和通常一些对象名以及对象地址等额外信息。
一个类可以通过重新定义__repr__()成员函数来控制自身实例关于这个函数的返回值。
str(object)返回一个表示对象的可打印的友好的字符串。
对于字符串来说,将返回自身。
与repr(object)区别在于,str(object)不尝试返回一个传递给eval()的字符串;
其目标是返回一个可打印的字符串。
如果没有给出参数,返回空字符串(同理对类,可通过__str__()成员控制其行为)

>>> print repr("hello world!")
'hello world!'
>>> print repr(10000L)
10000L
>>> print str("hello world!")
hello world!
>>> print str(10000L)
10000
>>> temp = 42
>>> print "the temperature is "+temp
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    print "the temperature is "+temp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "the temperature is "+ `temp`
the temperature is 42
>>> print "the temperature is " + repr(temp)
the temperature is 42

以上就是Python内置函数——repr & str的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。