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中文网(HdhCmsTestgxlcms测试数据)!
查看更多关于Python内置函数——repr&str的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did86246