• Python教程:str()和repr()的区别


    区别

    其实用处就是最大的区别了:str()主要用来为终端用户输出一些信息,而repr()主要用来调试;同时后者的目标是为了消除一些歧义(例如浮点数的精度问题),前者主要为了可读。
    使用

    In [12]: s = 'abc'
    
    In [13]: print(str(s))
    abc
    
    In [14]: print(2.0/11)
    0.18181818181818182
    
    In [15]: repr(s)
    Out[15]: "'abc'"
    
    In [16]: repr(2.0/11)
    Out[16]: '0.18181818181818182'
    

    仔细看一下,其实并没产生精度上的不同;但是当在Python2中就会发现区别了:

    >>> eval('2.0/11')
    0.18181818181818182
    >>> print(2.0/11)
    0.181818181818
    

    所以换个例子:

    #Python学习交流群:778463939
    
    In [17]: import datetime
    
    In [18]: n = datetime.datetime.now()
    
    In [19]: print(str(n)
        ...: )
    2020-01-16 09:22:13.361995
    
    In [20]: repr(n)
    Out[20]: 'datetime.datetime(2020, 1, 16, 9, 22, 13, 361995)'
    

    可以看到前者可读性更好,后者打印出来了类型和值,更适合调试;

    实现

    二者都通过内置函数实现;看看官方文档说repr()

    Return a string containing a printable representation of an object.
    
    A class can control what this function returns for its instances by defining a __repr__() method.
    

    意味着可以自定义这个函数,并实现自己的repr()(str同理),如下:

    In [35]: class TestClass:
        ...:     def __init__(self, name, age):
        ...:         self.name = name
        ...:         self.age = age
        ...:     def __repr__(self):
        ...:         return 'repr: ' + self.name + ' ,' + self.age
        ...:     def __str__(self):
        ...:         return self.name + ' ,' + self.age
        ...:
        
    In [38]: tt = TestClass('tony', '23')
    
    In [39]: repr(tt)
    Out[39]: 'repr: tony ,23'
    
    In [40]: str(tt)
    Out[40]: 'tony ,23'
    
  • 相关阅读:
    obj,lib,dll,exe
    .net连接access数据库 关键字引起的 语句的语法错误
    XSS攻击与防御
    location.href和location.replace和location.reload的不同(location.replace不记录历史)
    C++中头文件包含问题
    SqlServerExpress2005 自动备份
    在SQL Server 的使用过程中,发现几个很有用,但不太常用
    双机镜像
    浅谈SQL Server identity列的操作方法
    镜像三机
  • 原文地址:https://www.cnblogs.com/python960410445/p/13693640.html
Copyright © 2020-2023  润新知