Python内置函数——repr & str

黄舟
Lepaskan: 2017-01-19 16:45:31
asal
1370 orang telah melayarinya

Python内置函数——repr & str

repr & str

repr(object) & str(object)
Salin selepas log masuk

变量值被转换为字符串的两种机制:前者的目标是准确性,后者的目标是可读性
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 &#39;str&#39; and &#39;int&#39; objects
>>> print "the temperature is "+ `temp`
the temperature is 42
>>> print "the temperature is " + repr(temp)
the temperature is 42
Salin selepas log masuk

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


Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!