Why all string literals in python evaluate to single quote?
'a', "a", """a"""
all evaluate to
'a'
in the inter-active shell.
Why all string literals in python evaluate to single quote?
'a', "a", """a"""
all evaluate to
'a'
in the inter-active shell.
Not all unicode literals are printed using ''
, case in point, if you mix these, Python will use the appropriate quotation to represent it:
>>> "'a'"
"'a'"
Choosing ''
over ""
(not """ """
since those are less readable) for the case where no mixing of quotations is present is just a decision that was probably made very early on with no significant reasons behind it.
Python always chooses the '
over "
and those over """
when it can:
>>> """'a'"""
"'a'"
and there's no 'special' reasoning behind it.
You have to make a distinction between the content of a string and its representation.
The literals 'a'
, "a"
and """a"""
all represent the same string. So that means that after assigning that string, like:
t = "a"
Python no longer remembers how that string was entered. Furthermore for the string:
t = "a"+'b'
the resulting string is 'ab'
: there is simply no "original literal".
Now you query a variable (or an expression) in the terminal. The terminal will internally call the repr(..)
method. So basically, you have written:
repr("a")
Now Python calls the __repr__
method and that method inspects if there is a single quote in the string. If not, the string is represented with single quotes, otherwise it can be represented with double quotes. For instance:
>>> "'a'"
"'a'"