Python repr() 或str() 函数

Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。

函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的
语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()

等同的值。很多类型,诸如数值或链表、字典这样的结构,针对各函数都有着统一的解读方式。字符串和
浮点数,有着独特的解读方式。
Some examples:
下面有些例子
>>> 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'))"

人生有两种境界:一是痛而不言,二是笑而不语。痛而不言是一种智慧,人生在世,往往会因这样或那样的伤害而心痛不已。对坚强的人来说,累累伤痕是生命赐予的最好礼物;笑而不语是一种豁达,朋友间的戏虐,遭人误解后的无奈,过多的言辞申辩反让人觉得华而不实,莫不如留下一抹微笑,任他人作评。

repr的功能可以使用反引号实现·

>>> print "the temperature is " + tmp


Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    print "the temperature is " + tmp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "the temperature is " + 'tmp'
the temperature is tmp
>>> print "the temperature is " + `tmp`
the temperature is 42
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值