-1

Why all string literals in python evaluate to single quote?

'a', "a", """a"""

all evaluate to

'a'

in the inter-active shell.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
pypyad
  • 1
  • 3

2 Answers2

1

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
1

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'"
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • repr('a') does not produce 'a'? also is "a" and 'b' still in memory in addition to new 'ab' literal? – pypyad Mar 12 '17 at 15:44
  • @pypyad: `repr('a')` produces a string with **content `'a'`** and whether `'a'` and `'b'` remain in memory is a decision a Python interpreter makes. That is afaik not specified. – Willem Van Onsem Mar 12 '17 at 17:01