学习Python:repr和str的区分

基于Python 2.7.9 Docmentation中repr和str的说明 


repr(object)

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.
翻译如下:
返回一个表示对象的可打印的字符串。这和通过转换(反引号``)处理得到的结果一致。作为一个普通函数,可以使用这个运算有些时候是有用处的。对于大部分类型,这个函数尝试返回一个字符串,当其传给eval(),将生成同样的对象,(即eval(repr(object)==object.)否则生成一个用尖括号括起来的字符串,包含着对象类型名和通常一些对象名以及对象地址等额外信息。一个类可以通过重新定义__repr__()成员函数来控制自身实例关于这个函数的返回值。


class str(object='')

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, ''.
翻译如下:

返回一个表示对象的可打印的友好的字符串。对于字符串来说,将返回自身。与repr(object)区别在于,str(object)不尝试返回一个传递给eval()的字符串;其目标是返回一个可打印的字符串。如果没有给出参数,返回空字符串。(同理对类,可通过__str__() 成员控制其行为。)


注:eval(str)将字符串str当成有效的表达式来求值并返回计算结果

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值