Understanding the difference between Double Quote and Single Quote with __repr __ ()

What is the difference between print , object and repr() ? Why does it print in different formats?

See output difference :

 >>> x="This is New era" >>> print x # print in double quote when with print() This is New era >>> x # x display in single quote 'This is New era' >>> x.__repr__() # repr() already contain string "'This is New era'" >>> x.__str__() # str() print only in single quote '' 'This is New era' 
+5
source share
3 answers

There is no semantic difference between ' and " . You can use ' if the string contains " and vice versa, and Python will do the same. If the string contains both, you need to wrest some of them (or use triple quotes, """ or ''' ). (If both ' and " possible, Python and many programmers seem to prefer ' .)

 >>> x = "string with ' quote" >>> y = 'string with " quote' >>> z = "string with ' and \" quote" >>> x "string with ' quote" >>> y 'string with " quote' >>> z 'string with \' and " quote' 

About print , str and repr : print print the given line without additional quotes, while str will create a line from the given object (in this case the line itself) and repr create a "presentation object" from the object (i.e. a line containing a set of quotes). In a nutshell, the difference between str and repr should be that str easy to understand for the user, and repr easy to understand for Python.

Also, if you type an expression into an interactive shell, Python will automatically repeat the repr result. This can be a bit confusing: in the interactive shell, when you do print(x) , you see str(x) ; when you use str(x) , then you see repr(str(x)) , and when you use repr(x) , you see repr(repr(x)) (thus double quotes).

 >>> print("some string") # print string, no result to echo some string >>> str("some string") # create string, echo result 'some string' >>> repr("some string") # create repr string, echo result "'some string'" 
+5
source

See __repr__ :

Called by the built-in repr () function and string conversions (backticks) to compute the "official" string representation of an object. If at all possible, it should look like a valid Python expression that can be used to recreate an object with the same value (given the appropriate environment).

And __str__ :

Called by the built-in str () function and the print operator to compute an "informal" string representation of an object. This differs from __repr __ () in that it should not be a valid Python expression : a more convenient or concise representation may be used instead.

Accent added by me.

+1
source

__str__ and __repr__ are both ways of getting a string representation of an object. __str__ should be shorter and more user friendly, and __repr__ should provide more details.

However, in python, there is no difference between a single quote and a double quote.

0
source

Source: https://habr.com/ru/post/1243117/


All Articles