认识 str 和 repr 的区别
num = 521
r1 = str(num)
r2 = repr(num)
# str和repr函数都可以把其它类型的值转为字符串
# print(r1,type(r1)) # 输出: 521 <class 'str'>
# print(r2,type(r2)) # 输出:521 <class 'str'>
s = '521'
r1 = str(s)
r2 = repr(s)
print(r1,type(r1)) # 输出结果: 521 <class 'str'>
print(r2,type(r2)) # 输出结果:'521' <class 'str'>
# repr解析的结果带了引号
'''
str和repr函数都能够把其它类型的数据转为字符串类型
str函数会把对象 转为 更适合人类阅读的形式
repr函数会把对象 转为 解释器读取的形式
如果数据对象并没有更明显的区别的化,str和repr的结果是一样的
'''
class Demo():
def __str__(self):
return '123'
def __repr__(self):
return '123'
obj = Demo()
r1 = str(obj)
r2 = repr(obj)
print(r1,type(r1)) # 输出:123 <class 'str'>
print(r2,type(r2)) # 输出:123 <class 'str'>