首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

[D]python 例如42L和42有什么区别?求教,该怎么解决

2012-06-06 
[D]python例如42L和42有什么区别?求教具体一点啊,主要是repr和str的区别讲下----------------------------

[D]python 例如42L和42有什么区别?求教
具体一点啊,主要是repr和str的区别讲下
-------------------------------
Double行动:
原帖分数:20
帖子加分:20

[解决办法]
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'))"


[解决办法]
repr 
repr(object) 

返回一个可以用来表示对象的可打印字符串 

首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象 
否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址) 

一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。




str
str([object])

返回一个可以用来表示对象的可打印的友好的字符串

对字符串,返回本身。
没有参数,则返回空字符串
对类,可通过 __str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。

与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。


[解决办法]
简单的说,str给用户提供简单易懂的信息;repr提供更为详尽的对象信息,可以根据这些信息还原对象

热点排行