python str和repr的区别

如题所述

第1个回答  2020-05-04
str与repr区别:
1、python中str函数通常把对象转换成字符串,即生成对象的可读性好的字符串,一般在输出文本时使用,或者用于合成字符串。str的输出对用户比较友好适合print输出。
2、pyton中repr函数将一个对象转成类似源代码的字符串,只用于显示。repr的输出对python友好,适合eval函数得到原来的对象。
3、在类中实现__str__和__repr__方法,就可以得到不同的返回,示例代码:
>>> class test(object):
def __repr__(self):
return "return test repr() string."
def __str__(self):
return "return test str() string."
>>> print(str(test()))
return test str() string.
>>> print(repr(test()))
return test repr() string.
相似回答