Search code examples
pythonstringquotesdouble-quotes

Why does Python use different quotes for representing strings depending on their content?


In Python 2.7, I noticed that repr(s) (with s being a string) behavior differs depending on s's content.

Here is what I mean:

In [1]: print repr("John's brother")
"John's brother"

In [2]: print repr("system")
'system'

Note the different quotes type in both case.

From my tests it seems that whenever s contains a ' character, the represented string is quoted with " unless the string also contains an (escaped) " character.

Here is an example of what I mean:

In [3]: print repr("foo")
'foo'

In [4]: print repr("foo'")
"foo'"

In [5]: print repr("foo'\"")
'foo\'"'

Now I understand it makes no difference since repr is not to offer any guarantee about the exact output format but I'm curious as to why the Python developers decided those things:

  • Why is there two ways of quoting strings ?
  • Why bother with the specific logic for representing strings that contain quotes ? After all it makes things like doctests a bit more difficult to write.

Solution

  • Python tries to give the most "natural" representation of the string it's repr-ing.

    So, for example, it will use " if the string contains ' because "that's the ticket" looks better than 'that\'s the ticket'.

    And there are actually four ways to quote strings: single quotes — ' and " — and triple quotes — """ and '''. There are these four methods because it's nicer to to be able to write strings naturally without escaping things inside them.