
1、说明
__str__主要应用于print函数以及字符串函数str的转换操作
__repr__应用于所有输出操作,如果有print以及str操作并定义__str__,则会以__str__为准
__repr__与 __str__均未定义的时候,默认打印的是输出对象地址信息
2、实例
1 2 3 4 5 6 7 8 9 10 | # str.pyclass DisplayClass:
"" "
__repr__ is used everywhere, except by print and str when a __str__ is defined.
__str__ to support print and str exclusively
" ""
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电脑。