作用
在 Python 中要将某一类型的变量或者常量转换为字符串对象通常有两种方法,即 str()
或者 repr()
。
区别与使用
参考文章:Python 中 str() 和 repr() 函数的区别
函数 str()
用于将值转化为适于人阅读的形式,而 repr()
转化为供解释器读取的形式(如果没有等价的语法,则会发生 SyntaxError
异常), 适合开发和调试阶段使用。
>>> number = 123456789
>>> type(str(number))
<class 'str'>
>>> type(repr(number))
<class 'str'>
>>> print(repr(number))
123456789
>>> print(str(number))
123456789
两个函数返回的类型是相同的,值也是相同的。
>>> print(str('123456789'))
123456789
>>> print(repr('123456789'))
'123456789'
但当我们把一个字符串传给 str()
函数再打印到终端的时候,输出的字符不带引号。而将一个字符串传给 repr()
函数再打印到终端的时候,输出的字符带有引号。
造成这两种输出形式不同的原因在于:
print 语句结合 str()
函数实际上是调用了对象的 __str__
方法来输出结果。而 print 结合 repr()
实际上是调用对象的 __repr__
方法输出结果。下例中我们用 str
对象直接调用这两个方法,输出结果的形式与前一个例子保持一致。
>>> print('123456789'.__repr__())
'123456789'
>>> print('123456789'.__str__())
123456789
实战:自定义类的 str()
与 repr()
示例 1:仅在类中声明__str__
方法
自定义类如下:
class ValueTime:
value = -1
time = ''
def __init__(self, value, time):
self.value = value
self.time = time
def __str__(self):
return "ValueTime:value={}, time={}".format(self.value, self.time)
输出由ValueTime组成的list组成的list(list嵌套),实际输出的是对象的类名,并没有调用到自定义的__str__
方法。
[[<app.models.ValueTime instance at 0x0000000003E02AC8>, <app.models.ValueTime instance at 0x0000000003E02B08>, <app.models.ValueTime instance at 0x0000000003E02B48>, …], […], […], …]
示例 2:在类中声明__repr__
方法与__str__
方法
自定义类如下:
class ValueTime:
value = -1
time = ''
def __init__(self, value, time):
self.value = value
self.time = time
def __str__(self):
return "ValueTime:value={}, time={}".format(self.value, self.time)
def __repr__(self):
return "ValueTime:value={}, time={}".format(self.value, self.time)
输出由ValueTime组成的list组成的list(list嵌套),可以输出自定义格式化的对象,此时调用到了自定义的__repr__
方法。
[[ValueTime:value=22, time=2009-03-27, ValueTime:value=11, time=2009-03-30, ValueTime:value=22, time=2009-03-31, ValueTime:value=33, time=2009-04-01], […], […], …]