repr() 函数的功能是返回对象的规范字符串表达式,什么叫规范表达式呢???首先我们看看函数的声明:
1 2 3 4 5 6 7 8 |
def repr(p_object): # real signature unknown; restored from __doc__ """ repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. """ return "" |
好像并没有发现什么有用的信息,那就先看看 str() 函数吧。 str() 函数的功能则是将对象转换成一个字符串,准确的来说 str() 并不是一个函数,是一个类,字符串类 str,我们使用的时候会调去用 str 类的__init__() 方法,而__init__() 方法则是 python 中的构造函数,声明如下:
1 2 3 4 5 6 7 8 9 |
def __init__(self, string=""): # known special case of str.__init__ """ str(object="") -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. # (copied from class doc) """ pass |
它将会返回 a nice string!那么什么是 nice string?????这里我们来看个例子
1 2 3 4 5 6 7 8 |
>>> a = "hello" >>> b = "world" >>> print a, b hello world >>> print str(a), str(b) hello world >>> print repr(a), repr(b) "hello" "world" |
先定义两个字符串变量 a 和 b,把他们输出,可以发现,a 和 str(a) 输出完全一致,而 repr() 则会在外层包裹上单引号再输出,这里可能看起来还不是很明了,那么我们变换一下,把其中的一个 str 字符串变成 unicode 字符串类型:
1 2 3 4 5 6 7 8 |
>>> a = "Hello Wrold" >>> b = u"Hello World" >>> print a, b Hello Wrold Hello World >>> print str(a), str(b) Hello Wrold Hello World >>> print repr(a), repr(b) "Hello Wrold" u"Hello World" |
可以看到 str 还是和上面一样,话不多说直接输出,而 repr() 则会在外层加上 u""。
由此可以理解,规范表达式的意思就是输出对象的时候连通它本身是什么也输出来!
现在我们把英文字符串改成汉字试一试:
1 2 3 4 5 6 7 8 |
>>> a = "你好" >>> b = "世界" >>> print a, b 你好 世界 >>> print str(a), str(b) 你好 世界 >>> print repr(a), repr(b) "xc4xe3xbaxc3" "xcaxc0xbdxe7" |
在输出中文的时候,str() 输出的是还是和之前一样,是什么就输出什么,而 repr() 则会把汉字的编码以字符串形式输出,这就是 repr() 的功能——输出这个对象。
可以这么认为:函数 str() 会把对象转化为成方便人阅读的形式,而 repr() 会把对象转为计算机读取的形式!这就是它们最主要的区别。
当然,str() 和 repr() 还有更高级的用法,最常用就是可以帮我们直接将数值转化成字符串,就像 C/C++里面的 itoa() 函数一样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> a = 123 >>> b = 234.567 >>> print a, type(a) 123 <type "int"> >>> print b, type(b) 234.567 <type "float"> >>> print str(a), type(str(a)) 123 <type "str"> >>> print str(b), type(str(b)) 234.567 <type "str"> >>> print repr(a), repr(b) 123 234.567 >>> print type(repr(a)), type(repr(b)) <type "str"> <type "str"> |
四不四灰常方便呀~
评论