Python str() 与 repr() 的区别
来源:互联网 发布:霸主软件 编辑:程序博客网 时间:2024/05/16 05:46
尽管str(),repr()和``运算在特性和功能方面都非常相似,事实上repr()和``做的是完全一样的事情,它们返回的是一个对象的“官方”字符串表示,也就是说绝大多数情况下可以通过求值运算(使用内建函数eval())重新得到该对象。
但str()则有所不同,str()致力于生成一个对象的可读性好的字符串表示,它的返回结果通常无法用于eval()求值,但很适合用于print语句输出。需要再次提醒的是,并不是所有repr()返回的字符串都能够用 eval()内建函数得到原来的对象。 也就是说 repr() 输出对 Python比较友好,而str()的输出对用户比较友好。
虽然如此,很多情况下这三者的输出仍然都是完全一样的。 大家可以看下下面的代码,来进行对比
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print s
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print hellos
'hello, world\n'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print s
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print hellos
'hello, world\n'
阅读全文
0 0
- python 中 str() 与 repr() 的区别
- python中str()与repr()的区别
- python str与repr的区别
- Python str() 与 repr() 的区别
- str()与repr()的区别
- str与repr的区别
- [python]python中str()与repr()的区别与联系
- Python菜鸟晋级03----repr() 与str() 函数的区别
- python核心编程:repr()与str()的区别
- python学习 str与repr区别
- 区别python 的str和repr
- python之repr()和str()的区别
- python之repr()和str()的区别
- python str和repr 的区别
- python str和repr的区别
- python str和repr的区别
- python str和repr的区别
- Python str 和 repr 的区别
- 从千团大战到网贷战国,烧钱千亿背后的底层用户增长逻辑
- java生成图表格式图片(1)
- 线段树的入门-Poj2528(简单线段树和简单离散化)
- 在VS2010下配置QT5.0.2
- 关于http协议请求报文伪造响应的方法
- Python str() 与 repr() 的区别
- 自定义view 圆 加速减速
- iOS WKWebView中显示进度条及HTML的title
- 海航集团王健帮助海航集团成立慈航基金会——中国企业家的典范
- hdu 1257 最少拦截系统
- SQL Server 数据库性能优化
- 前端基础-08-数据类型高阶函数
- ajax异步验证用户名
- 光棍节专题:python程序员如何找女朋友