Skip to content Skip to sidebar Skip to footer

Understanding Difference Between Double Quote And Single Quote With __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

Solution 1:

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 reprcreates 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'"

Solution 2:

__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.

Post a Comment for "Understanding Difference Between Double Quote And Single Quote With __repr__()"