pythonsyntaxstring-literals

What is the difference between single, double, and triple quotes in Python?


In other words, how do I know which one to use?

I know when I use strings. I would do

    string = "This is a string"

When would I use ' ' or """ """?


Solution

  • '...' and "..." are equivalent. If you have an apostrophe in the string, it is easier to use "..." so you don't have to escape the apostrophe. If you have quotes in the string, it's easier to use '...' so you don't have to escape the quotes.

    Triple quotes (both varieties, """ and ''' are permitted) allow the string to contain line breaks. These are commonly used for docstrings (and other multi-line comments, including "commenting out" code) and for embedded snippets of other computer languages such as HTML and SQL. They can also be useful for string literals that contain both quotes and apostrophes.

    https://docs.python.org/2.0/ref/strings.html