【python-笔记】python核心编程第四章之repr()与str()之间的区别

repr
repr(object)

返回一个可以用来表示对象的可打印字符串

首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象
否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址)
一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。

Python 手册:

Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.

str
str([object])

返回一个可以用来表示对象的可打印的友好的字符串

对字符串,返回本身。
没有参数,则返回空字符串
对类,可通过 __str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。

与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。

Python 手册:

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, .


其他
python2 中:

__repr__()
 如前所述
 
__str__()
 如前所述,返回字符串(字节流)
 
__unicode__()
 返回unicode字符串
 

实现类时,应该实现 __unicode__(),然后提供了一个某种编码的 __str__()


def __str__(self):    return unicode(self).encode('utf-8')
在python3中: __str__() 直接就是 unicode,字节流由__bytes__()提供。

参考
http://docs.python.org/library/functions.html

http://stackoverflow.com/questions/1307014/python-str-versus-unicode
 

 

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10420169/viewspace-686980/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10420169/viewspace-686980/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值