您的位置:首页 > 编程语言 > Python开发

python str和repr 的区别

2015-11-01 16:52 597 查看
一、 文档说明

str

str(object=”) -> string

Return a nice string representation of the object. If the argument is

a string, the return value is the same object.

返回一个可以表示对象的友好的可打印的字符串。对于字符串则返回本身,如果没有参数,则返回空字符串。str返回的对象更适合我们人类阅读(可以这么理解),str致力于返回一个可读性比较好的对象,返回的结果通常不会通过eval()去处理。

repr

repr(object) -> string

Return the canonical string representation of the object.

For most object types, eval(repr(object)) == object.

返回一个可以表示对象的可打印的字符串,首先会生成一个这样的字符串,然后将其传给eval()可以重新生成同样的对象。但是repr所返回的对象更适合于解释器去阅读,可以理解为亲近与python。

二、 举个粟子:

>>> a = 'Hello,kitty!'
>>> str(a)
'Hello,kitty!'            #字符串str会返回本身
>>> repr(a)
"'Hello,kitty!'"
>>> a = 'Hello,kitty!\n'
>>> b = repr(a)
>>> print b
'Hello,kitty!\n'
>>> c = str(a)
>>> print c
Hello,kitty!
>>>


引用:http://www.linuxidc.com/Linux/2014-01/95259.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: