str()和repr()都被用来获得一个对象的字符串表示。
1. str和repr不同
看个例子
str():
s = 'Hello, Geeks.'
print str(s)
print str(2.0/11.0)
output:
Hello, Geeks.
0.181818181818
repr():
s = 'Hello, Geeks.'
print repr(s)
print repr(2.0/11.0)
output:
'Hello, Geeks.'
0.18181818181818182
上面的例子中,repr()返回的字符串多了一对引号,返回的float类型精度也更高。
str和repr的区别
str被用作为终端用户创建输出;而repr()被主要用来开发调试。repr的目的是清晰;str的目的是可读。repr()用来获得一个对象的正式(offical)字符串;str()用来获得一个对象的非正式(informal)字符串。- 在对象内部,
str()内建函数使用__str__()来展示对象的字符串表示;repr()内建函数使用__repr__()来展示对象。
再看个例子
code:
import datetime
today = datetime.datetime.now()
# Prints readable format for date-time object
print str(today)
# prints the official format of date-time object
print repr(today)
output:
2016-02-22 19:32:04.078030
datetime.datetime(2016, 2, 22, 19, 32, 4, 78030)
2. 自定义类中使用它们
class Complex:
# Constructor
def __init__(self, real, imag):
self.real = real
self.imag = imag
# For call to repr(). Prints object's information
def __repr__(self):
return 'Rational(%s, %s)' % (self.real, self.imag)
# For call to str(). Prints readable form
def __str__(self):
return '%s + i%s' % (self.real, self.imag)
Ref
本文详细对比了Python中str和repr两个内置函数的功能和用途。str主要用于生成用户友好的字符串输出,而repr则用于生成可用于调试的正式字符串表示。文章通过多个实例展示了两者之间的区别,并解释了如何在自定义类中实现这两种表示。

873

被折叠的 条评论
为什么被折叠?



