菜鸟求大大们解释Python里str函数和repr函数的区别

 我来答
qinhanmin
推荐于2016-07-20 · 超过42用户采纳过TA的回答
知道小有建树答主
回答量:67
采纳率:100%
帮助的人:70.1万
展开全部
简单来说
str()将数值转成字符串
repr()将对象转成字符串显示,注意只是显示,有些对象转成字符串没有意义。如list,dict使用str()是无效的,但使用repr可以,这是为了显示他们的值

以下内容摘自google
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'))"
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式