zoukankan      html  css  js  c++  java
  • repr() Vs str()

    在python中,将对象转换为字符串有两个内建函数: str Vs repr .
    str 是一个友好的,人们可读的字符串。repr 应该包含关于对象内容的详细信息(有时他们会返回相同的内容,例如整数)。
    按照惯例。如果有一个python表达式将评估另一个 == 对象,repr 将会返回这样的表达式,
    >>> print(repr("hi"))
    "hi" # notice the quotes here as opposed to ...
    >>> print(str("hi"))
    hi
    If returning an expression doesn't make sense for an object, repr should return a sting
    that's surround by <and> symbols e.g. <blsh>
    To answer your original question:
    %s <-> str
    %r <-> repr

    in addition:
    You can control the way an instance of your own classes convert to string by implemrnting
    __str__ and __repr__ methods.


    class Foo:
    def __init__(self, foo):
    self.foo = foo
    def __eq__(self, other):
    """ Implements == ."""
    return self.foo = other.foo

    def __repr__(self):
    #if you eval the return value of this function,
    #you'll get another Foo instance that's == to self
    return "Foo(%r)" % self.foo

    Adding to the replies given above, '%r' can be useful in a scensrio where you have
    a list with heterogeous data .Let's say ,we have a
    List = [1,'apple', 2, 'r', 'banana'] Obviously in this case using
    '%d' or '%s' would cause an error .instead, we can use '%r' to
    print all these value.

    Python 有办法将任意值转为字符串:将它传入repr() 或str() 函数。

    函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式(如果没有等价的
    语法,则会发生SyntaxError 异常) 某对象没有适于人阅读的解释形式的话, str() 会返回与repr()

    等同的值.

    __repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。

    • 打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),它通常应该返回一个友好的显示。

    • __repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,如果没有使用__str__,会使用print和str。它通常应该返回一个编码字符串,可以用来重新创建对象,或者给开发者详细的显示。

    当我们想所有环境下都统一显示的话,可以重构__repr__方法;当我们想在不同环境下支持不同的显示,例如终端用户显示使用__str__,而程序员在开发期间则使用底层的__repr__来显示,实际上__str__只是覆盖了__repr__以得到更友好的用户显示。

     

    尽管str(),repr()和``运算在特性和功能方面都非常相似,事实上repr()和``做的是完全一样的事情,它们返回的是一个对象的“官方”字符串表示,也就是说绝大多数情况下可以通过求值运算(使用内建函数eval())重新得到该对象,但str()则有所不同。str()致力于生成一个对象的可读性好的字符串表示,它的返回结果通常无法用于eval()求值,但很适合用于print语句输出。需要再次提醒的是,并不是所有repr()返回的字符串都能够用 eval()内建函数得到原来的对象。 

    也就是说 repr() 输出对 Python比较友好,而str()的输出对用户比较友好。虽然如此,很多情况下这三者的输出仍然都是完全一样的。 

  • 相关阅读:
    Spring+Mybatis配置
    Python 字符串
    图像处理知识相关
    CUDA编程学习相关
    Pthon学习相关
    【论文阅读】ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices
    【pytorch】pytorch学习笔记(一)
    【论文阅读】MEAL: Multi-Model Ensemble via Adversarial Learning
    【论文阅读】HydraPlus-Net: Attentive Deep Features for Pedestrian Analysis
    【论文阅读】Learning Spatial Regularization with Image-level Supervisions for Multi-label Image Classification
  • 原文地址:https://www.cnblogs.com/Davirain/p/8764959.html
Copyright © 2011-2022 走看看