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