Python repr() 函数和str() 函数

Python 有2种办法将任意值转为字符串:repr()函数 或 str()函数。
>>> help(repr)
Help on built-in function repr in module __builtin__:
repr(...)
    repr(object) -> string
    
    Return the canonical(标准的,规范的) string representation(表示,表现) of the object.

    For most object types, eval(repr(object)) == object.


函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的
语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()
等同的值。很多类型,诸如数值或链表、字典这样的结构,这2个函数都有着统一的解读方式。特别的是,字符串和
浮点数,有着不同的解读方式。
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.

1》
>>> str(8)
'8'
>>> repr(8)
'8'
>>> str(9.9)
'9.9'
>>> repr(9.9)
'9.9'
>>> t=(1,2,3)
>>> str(t)
'(1, 2, 3)'
>>> repr(t)
'(1, 2, 3)'
>>> l=[3,4,5]
>>> str(l)
'[3, 4, 5]'
>>> repr(l)
'[3, 4, 5]'
>>> d={'name':'song','age':26}
>>> d
{'age': 26, 'name': 'song'}
>>> str(d)
"{'age': 26, 'name': 'song'}"
>>> repr(d)
"{'age': 26, 'name': 'song'}"
>>> 
2》
>>> s='hello,python'
>>> str(s)
'hello,python'
>>> repr(s)
"'hello,python'"
>>> str(1/7.0)
'0.142857142857'
>>> repr(1/7.0)
'0.14285714285714285'
3》
>>> s='my name is '+repr(25)+' and his name is '+str(26)
>>> s
'my name is 25 and his name is 26'
>>> 
4》The repr() of a string adds string quotes(引号) and backslashes(反斜杠):
>>> s='hello world\n'
>>> str(s)
'hello world\n'
>>> repr(s)
"'hello world\\n'"
>>> s1=str(s)
>>> s2=repr(s)
>>> s1
'hello world\n'
>>> s2
"'hello world\\n'"
>>> print s1

hello world


>>> print s2
'hello world\n'
>>> 
5》The argument to repr() may be any Python object:
>>> x=10
>>> y=20
>>> repr([x,y,('name','age')])
"[10, 20, ('name', 'age')]"
>>> 
6》repr函数用来取得对象的规范字符串表示。 反引号(也称转换符)可以完成相同的功能。注
意,在大多数时候有eval(repr(object)) == object。
>>> l=['name','age']
>>> repr(l)
"['name', 'age']"
>>> `l`
"['name', 'age']"
>>> str(l)
"['name', 'age']"

>>> 

7》

>>> 9==eval(repr(9))
True

>>> 9.099==eval(repr(9.099))
True

>>> d
{'age': 26, 'name': 'song'}
>>> d==eval(repr(d))
True

>>> l
['name', 'age']
>>> l==eval(repr(l))
True

>>> 9==eval(str(9))
True
>>> 9.099==eval(str(9.099))
True
>>> d
{'age': 26, 'name': 'song'}
>>> d==eval(str(d))
True
>>> l
['name', 'age']
>>> l==eval(str(l))
True
>>> 

(完)

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值