Python Strings

A ‘ and ” are interpreted as being the same in Python. “”” delimits a multi-line string. There is no reason to use one style of string delimiter over the other, although I personally follow the style presented by Will Harris in StackOverflow (see bottom for summary).

'Hello World!'      # Returns 'Hello World!'
"Hello World!"      # Returns 'Hello World!'
"""Hello World!"""  # Returns 'Hello World!'

'Hello              # Error: ' doesn't support unescaped newlines
World!'

'Hello\nWorld!'     # Returns 'Hello\nWorld!'

"Hello              # Error: " doesn't support unescaped newlines
World!"

"Hello\nWorld!"     # Returns 'Hello\nWorld!'

"""Hello            # Returns 'Hello\nWorld!'
World!"""

"""Hello\nWorld!""" # Returns 'Hello\nWorld!'

'Hello' + ' ' + 'World!'      # Returns 'Hello World!'

'%s %s!' % ('Hello', 'World') # Interpolation, returns 'Hello World!'
Will Harris’ style for Python string, summary
  • Single quotes for small symbol-like strings.
  • Double quotes around strings that are used for interpolation or that are natural language messages.
  • Triple double quotes for docstrings and raw string literals for regular expressions.
  1. 15/03/2011 at 06:47

    I tend to use single quotes wherever possible. One reason for this is that single quotes preserve any double quotes in the string without having to escape them.

    ‘You said, “Hello World”‘

    Conversely double quotes preserve single quotes.

    “This won’t work with single quotes.”

    Triple quotes avoid both problems and allow embedded newlines.

    “””Both solutions above won’t work
    when a string contains ” and ‘.”””

    Of course you can always use the escape character too.

    ‘The single quote in this string won\’t end the string.’

    • 15/03/2011 at 08:12

      That’s a valid point, I would think that this is the other major convention regarding quotation in Python. Personally, I like the idea of using different quotes in different contexts, as it tends to give a level of semantic meaning to what would otherwise be dead string literals.

      • 16/03/2011 at 02:48

        I agree, this is the first time I’ve come across that convention, and I’ll probably start using it in the future. Unlike some in the stackoverflow thread, though I don’t see the value in sticking with it at all costs and filling my strings with escape characters.

  1. No trackbacks yet.

Leave a comment