1、说明
__str__主要用于print函数和字符串函数str的转换操作
__repr如果有print和str操作并定义__,则应用于所有输出操作str___________str__为准
__repr__与 __str__当未定义时,默认打印输出对象地址信息
2、实例
#str.pyclassDisplayClass: """ __repr__isusedeverywhere,exceptbyprintandstrwhena__str__isdefined. __str__tosupportprintandstrexclusively """ def__repr__(self): return"display__repr__class" def__str__(self): return"display__str__class"#以命令行的形式打印输出2.x&3.x输出效果一致,以2.x作为截图>>>d=DisplayClass()>>>d#调用repr>>>print(d)#调用str>>>print(repr(d))#调用repr>>>print(str(d))#调用str
以上是python打印字符串的方法,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。