python的str()和repr()的区别
来源:互联网 发布:淘宝网兼职赚钱 编辑:程序博客网 时间:2024/05/15 03:42
str()一般是将数值转成字符串。
repr()是将一个对象转成字符串显示,注意只是显示用,有些对象转成字符串没有直接的意思。如list,dict使用str()是无效的,但使用repr可以,这是为了看它们都有哪些值,为了显示之用。
The str() function is meant to return representations of values which are fairly
human-readable, while repr() is meant to generate representations which can be read by
the interpreter (or will force a SyntaxError if there is not equivalent syntax). For
objects which don't have a particular representation for human consumption, str() will
return the same value as repr(). Many values, such as numbers or structures like lists
and dictionaries, have the same representation using either function. Strings and
floating point numbers, in particular, have two distinct representations.
Some examples:
>>> 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'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
>>> # reverse quotes are convenient in interactive sessions:
... `x, y, ('spam', 'eggs')`
"(32.5, 40000, ('spam', 'eggs'))"
翻译:
Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。
(如果没有等价的语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
>>> 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'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
- 区别python 的str和repr
- python之repr()和str()的区别
- python之repr()和str()的区别
- python str和repr 的区别
- python str和repr的区别
- python str和repr的区别
- python str和repr的区别
- Python str 和 repr 的区别
- python的str()和repr()的区别
- str()和repr()的区别
- str() 和repr()的区别
- str和repr的区别
- str和repr的区别
- str和repr的区别
- str和repr的区别
- Python的str()和repr()
- Python里str函数和repr函数的区别
- Python里str函数和repr函数的区别
- 通过rpm包安装、配置及卸载mysql
- JES与OIM的集成
- QT 获取系统屏幕分辨率
- MySql存储过程—1、SQL存储过程的基础知识
- AnimationSet----动画复合器简单概念
- python的str()和repr()的区别
- Linux-Qt - 程序界面大小自适应屏幕分辨率
- 获取音视频文件播放时长
- 【Visual C++】游戏开发笔记十三 游戏输入消息处理(二) 鼠标消息处理
- IOS_MaxRects算法在ScrollView中应用Demo
- poj1068
- 轻量级C语言实现的minixml解析库入门教程
- preg_match正则表达式匹配 && 正则表达式
- 社会实践报告 —我的东软之旅