1.%s,%r The difference between

When formatting output ,%r And %s The difference is like repr() Functions deal with objects and str() Functions handle differences in objects .

  • %s ⇒ str(), Comparative intelligence ;
  • %r ⇒ repr(), The treatment is simple and direct ;

When dealing with some simple objects , There is little difference between the two , This paper focuses on some different usages of the two :

1.1 When processing strings

>> s = 'world'
>> print('hello %s'%s)
hello world
>> print('hello %r'%s)
hello 'world' >> str(s)
'world'
>> repr(s)
"'world'"

1.2   datetime In the library datetime object

>> from datetime import datetime
>> timeinfo = datetime.today() >> timeinfo
datetime.datetime(2017, 11, 23, 11, 19, 24, 840479)
>> type(timeinfo)
datetime.datetime >> repr(timeinfo)
'datetime.datetime(2017, 11, 23, 11, 19, 24, 840479)'
>> str(timeinfo)
'2017-11-23 11:19:24.840479'

2.__str__,__repr__ The difference between

class Test(object):
def __init__(self, value='hello, world!'):
self.data = value >>> t = Test()
>>> t
<__main__.Test at 0x7fa91c307190>
>>> print t
<__main__.Test object at 0x7fa91c307190> # Did you see that? ? It's not very friendly to print class objects , Shows the memory address of the object
# Let's refactor this class __repr__ as well as __str__, Look at the difference between them # restructure __repr__
class TestRepr(Test):
def __repr__(self):
return 'TestRepr(%s)' % self.data >>> tr = TestRepr()
>>> tr
TestRepr(hello, world!)
>>> print tr
TestRepr(hello, world!) # restructure __repr__ After the method , Whether output objects directly or through print All the printed information is according to our __repr__ Method is displayed in the format defined in
# Actually, it's because I didn't find __str__ Method , With __repr__ Method
# restructure __str__
calss TestStr(Test):
def __str__(self):
return '[Value: %s]' % self.data >>> ts = TestStr()
>>> ts
<__main__.TestStr at 0x7fa91c314e50>
>>> print ts
[Value: hello, world!] # You'll find that , Direct output object ts It didn't press us __str__ Method , While using print The output has changed

3. summary

Built-in functions str() and repr() (representation, expression , Express ) Or the back quote operator (``) You can easily get the content of the object in the form of string 、 type 、 Numerical attributes and so on .str() Function to get a good readability string ( So it was print call ), and repr() Function can be used to retrieve the object , Usually obj==eval(repr(obj)) This equation holds . These two functions take an object as their argument , Returns the appropriate string .

in fact repr() and `` Do the same thing , Returns the “ official ” String representation . The result is that most of the time ( Not all ) It can be evaluated ( Built-in functions eval()) Get the object back .

str() Is different , It generates a readable string representation of the object , The results are usually not available eval() evaluation , But suitable for print Output .

>>> class D(object):
... def __str__(self):
... return "a __str__"
... def __repr__(self):
... return "a __repr__"
...
>>> dr = D()
>>> print(dr)
a __str__
>>> dr
a __repr__
>>> "%s" % dr
'a __str__'
>>> "%r" % dr
'a __repr__' # Be careful __repr__ Methods not only affect repr() It also affects %r Format output .str In the same way

Why repr() It also needs to be ``? 

Python in , Some operators and functions do the same thing , The reason is that in some cases functions are more suitable than operators , For example, function objects can be passed as parameters . Double star (**) Power operation and pow() Built in functions all return x Of y Power .

python Medium %s,%r,__str__,__repr__ More articles about

  1. python Chinese magic method __init__,__str__,__del__ Detailed use of

    1. python The magic method in , similar __init__, __str__ wait , These built-in specific methods will be called automatically when they perform specific operations 2. __init__ How to use class Class name (object):  ...

  2. About Python In the middle with the letters r, Or letters u Starting string

      (1) With r or R At the beginning Python The string in represents ( Not escaped ) Original string python The characters inside , If there's one at the beginning r, such as : (r'^time/plus/\d{1,2}/$', hours_ahead) ...

  3. python The use of escape in English r&#39;&#39;

    Multiple characters need to be converted in the code ,, have access to r'' Example : print(r"'''\\sfd/;fe'lsdfl")

  4. Python in %s and %r The difference between

    Used earlier Python At work , For formatted output %s and %r It's all mixed use . This time it went wrong : cu.execute("insert into ipPool values(null, '%r ...

  5. Python in __repr__ and __str__ difference

    Python in __repr__ and __str__ difference Just look at the following example class Test(object): def __init__(self, value='hello, world!'): ...

  6. python in __str__ And __repr__

    (1) background python in , For classes ( Custom class ) The default display of instance objects for is not very useful , It's not beautiful . such as : class adder: def __init__(self,value=0): self.data ...

  7. python Chinese magic method __str__ And __repr__ The difference between

    Raise questions When we customize a class , Print the class object or input it directly in interactive mode and press enter , The information displayed by default seems to be of little use . As shown below In [1]: class People: ...: def __in ...

  8. python Object-oriented programming ------4: Class basic special methods __str__,__repr__,__hash__,__new__,__bool__,6 The big comparison method

    One :string relevant :__str__(),__repr__(),__format__() str The method is more human oriented ,print() What you use is str repr The way is more to face python, The goal is to generate a ...

  9. Quickly understand Python In the string formatting method using percent sign placeholders in %s and %r The difference between the output content of

    <Python In the string formatting method using percent sign placeholders in %s and %r What's the difference between the output of ?> The old ape introduced the difference between the two , For quick understanding , Old ape here uses another way to add : 1. Use %r Is to call objec ...

Random recommendation

  1. Spring Integrate MyBatis

    This article is original. , The original address is http://www.cnblogs.com/fengzheng/p/5045105.html If you feel Hibernate inflexible , You can try Mybatis. Compared with Hibernat ...

  2. IOS Development encounters (null) And &lt;null&gt; Handle with ease

    stay ios During the development, we will inevitably encounter the null value returned by the server , But if it is nil Even if it doesn't matter, it's still possible to get (null) as well as <null> The return value of , How to deal with it ?( Of course, some dictionaries have been transferred to the model , It can be done through traversal and so on ) ...

  3. C# Learning notes ( 8、 ... and )—— Define the members of a class

    One . Definition of members 1. Define fields class Myclass { public int MyInt; } have access to readonly keyword , Indicates that this field can only be assigned during the execution of the constructor , Or it can be assigned by the initialization statement . ...

  4. emacs Shortcut notes

    C-d C-aM-aC-eM-e=== Copy and paste M-d    kill-wordM-del     backward-kill-wordM-k     kill-sentenceC-x del back ...

  5. Talking about Scala The use of underline in

    Scala As a functional programming language , For the students who are used to the instruction programming language , I'm not used to it , Besides the way of thinking , There's also the grammatical level , such as  underscore( Underline ) It will appear on many occasions , Make beginners quite confused , Today ...

  6. Linux Next mv Detailed command

    mv Command format :mv [ Options ]  Source file or directory   Target file or directory mv Command parameter ( Options ): -b : If you need to overwrite the file , Backup before overwriting . -f :force  The meaning of coercion , If the target file already exists , Don't ask and cover directly : ...

  7. Python The road of the whole stack ( Catalog ) - With information ( Continuous updating )

    One . Python The road of the whole stack - Catalog Python Basics Python Advanced Network programming Concurrent programming front end database Python Web Framework Django Front end frame Vue Linux Flask+ Intelligent toy ...

  8. Flask Develop a micro movie website ( 6、 ... and )

    1. Implementation of background management login function 1.1 Background management page login form LoginForm stay app Of admin Create under directory forms.py file , For preservation admin Forms to be used in blueprints from flask_wtf ...

  9. 067、 How to deploy Calico The Internet (2019-04-10 Wednesday )

    Reference resources https://www.cnblogs.com/CloudMan6/p/7509975.html   Calico  It's a pure three-layer virtual network solution ,Calico Assign one to each container IP, Every host All are ...

  10. php Two dimensional arrays are sorted by a key

    $date = array_column($arr, 'run_date'); // The results from above :array(0=>'2017-11-21',1=>'2017-11-20',3=> ...