首页 > 文章列表 > python打印字符串的方法

python打印字符串的方法

python打印字符串
300 2022-08-07

1、说明

__str__主要应用于print函数以及字符串函数str的转换操作

__repr__应用于所有输出操作,如果有print以及str操作并定义__str__,则会以__str__为准

__repr__与 __str__均未定义的时候,默认打印的是输出对象地址信息

2、实例

# 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

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。