Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding difference between Double Quote and Single Quote with __repr__()

Tags:

python

repr

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

See the 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'
like image 646
Mushahid Khan Avatar asked Feb 16 '16 09:02

Mushahid Khan


1 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 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'"
like image 114
tobias_k Avatar answered Sep 24 '22 07:09

tobias_k