What is the difference between print
, object
, and repr()
?
Why is it printing in different formats?
See the output differ
See __repr__:
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
And __str__:
Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead.
Emphasis added by me.
__str__
and __repr__
are both methods for getting a string representation of an object. __str__
is supposed to be shorter and more user-friendly, while __repr__
is supposed to provide more detail.
However, in python there is no difference between single quote and double quote.
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 have to escape some of them (or use triple quotes, """
or '''
). (If both '
and "
are possible, Python and many programmers seem to prefer '
, though.)
>>> 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
will print the given string with no additional quotes, while str
will create a string from the given object (in this case, the string itself) and repr
creates a "representation string" from the object (i.e. the string including a set of quotes). In a nutshell, the difference between str
and repr
should be that str
is easy to understand for the user and repr
is easy to understand for Python.
Also, if you enter any expression in the interactive shell, Python will automatically echo the repr
of the result. This can be a bit confusing: In the interactive shell, when you do print(x)
, what you see is str(x)
; when you use str(x)
, what you see is repr(str(x))
, and when you use repr(x)
, you see repr(repr(x))
(thus the 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'"