-1

New to python and I am learning this tutorial: http://learnpythonthehardway.org/book/ex8.html

I just cannot see why the line "But it didn't sing." got printed out with double-quote and all the others got printed with single quote.. Cannot see any difference from the code...

Shawn Li
  • 99
  • 2
  • 13
  • possible duplicate of [Single quotes vs. double quotes in Python](http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python) – Zulu Dec 31 '14 at 08:24

3 Answers3

1

The representation of a value should be equivalent to the Python code required to generate it. Since the string "But it didn't sing." contains a single quote, using single quotes to delimit it would create invalid code. Therefore double quotes are used instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • "using single quotes to delimit it would create invalid code" is a bit misleading. Of course, escaping would be necessary then, and using `"` removes the need for escaping and makes things more readable. – glglgl Dec 31 '14 at 08:29
1

The quotes depends on the string: if there are no quotes, it will use simple quotes:

>>> """no quotes"""
'no quotes'

if there is a single quote, it will use double quotes:

>>> """single quote:'"""
"single quote:'"

if there is a double quote, it will use single quotes:

"""double quote:" """ 'double quote:" '

if there are both, it will use single quotes, hence escaping the single one:

>>> """mix quotes:'" """
'mix quotes:\'" '
>>> """mix quotes:"' """
'mix quotes:"\' '
>>> '''mix quotes:"' '''
'mix quotes:"\' '

There won't be a difference though when you print the string:

>>> print '''mix quotes:"' '''
mix quotes:"'

the surroundings quotes are for the representation of the strings:

>>> print str('''mix quotes:"' ''')
mix quotes:"'
>>> print repr('''mix quotes:"' ''')
'mix quotes:"\' '

You might want to check the python tutorial on strings.

fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

Python has several rules for outputting the repr of strings.

Normally, it uses ' to surround them, except if there are 's within it - then it uses " for removing the need of quoting.

If a string contains both ' and '"characters, it uses's and quotes the"`.

As there can be several valid and equivalent representations of a string, these rues might change from version to version.

BTW, in the site you linked to the answer is given as well:

Q: Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?

A: Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.

glglgl
  • 89,107
  • 13
  • 149
  • 217