首页 >后端开发 >Python教程 > 正文

Python内置函数——repr & str

原创2017-01-19 16:45:310522

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中文网(m.sbmmt.com)!

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

相关文章

相关视频


网友评论

文明上网理性发言,请遵守 新闻评论服务协议

我要评论
  • 专题推荐

    作者信息

    黄舟

    人生最曼妙的风景,竟是内心的淡定与从容!

    最近文章
    php实现字符串匹配算法之sunday算法的示例3305
    css中关于hideFocus的使用详解3351
    JavaScript中filter函数的详细介绍3124
    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类