Python Single vs. Double Quotes – Which Should You Use And Why?

This article was first published on Python - Better Data Science , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Python Single vs. Double Quotes - Which Should You Use And Why?

Python oftentimes leaves you with options, and quotes are no exception. What are the differences between Python single and double quotes? Which one should you use? When does one have an edge over the other? What are triple quotes? It's easy to get confused if you're a beginner.

You see, Python is a lot different from, let's say Java. In Java, you must use double quotes for strings, and are only allowed to use single quotes for characters. That's not the deal with Python. You have much more flexibility than in statically-typed languages. But is it actually a good thing? Continue reading to find out.

Don't feel like reading? Watch my video instead:


What are Single Quotes used for in Python?

In Python, it's a best practice to use single quotes to surround small and short strings, such as string literals or identifiers. But here's the deal – it's not a requirement. You can write entire paragraphs and articles inside single quotes.

Here are a couple of examples:

name = 'Bob'
print(name)

channel = 'Better Data Science'
print(channel)

paragraph = 'Bob likes the content on Better Data Science. Bob is cool. Be like Bob.'
print(paragraph)
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 1 – Single quotes example (image by author)

There's no character limit set for the content between single quotes, but there are a few gotchas you'll inevitably run into. The first one is a quotation mark inside a string.

The Problem with Quotation Marks inside a String

The English language is full of single quotation marks (apostrophes). For example, I can write we are or we're, and both represent the same thing. Opting for the second option is problematic if you want to use single quotes to surround strings in Python:

print('We're going skiing this winter.')
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 2 – Syntax error when printing a string with quotation marks (image by author)

Python thinks the string ends after We, so everything after it is considered a syntactical error. You can easily spot errors like these in code editors, as the part after We is colored differently.

There are three ways around it:

  1. Stop using contractions (we are -> we're) – Not practical at all.
  2. Escape a string – A possibility we'll explore next.
  3. Use double quotation – Something we'll cover later.

Escaping a String in Python

The main idea behind escaping a string is preventing certain characters from being used as a part of the programming language. For example, we don't want the apostrophe treated as a quotation mark.

In Python, you can use the backslash (\) sign to escape a string character:

print('We\'re going skiing this winter.')
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 3 – Escaping a character in Python (image by author)

That's cool, but backslash is often used as a literal character in strings – for example, to represent a path on a computer. Let's see what happens if you try to print a path using the escape character:

print('C:\Users\Bob')
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 4 – Syntax error when using invalid escape character (image by author)

Probably not what you wanted to see. As it turns out, you can escape the escape character in two ways:

  1. By using a raw string – Write r before the first quotation mark.
  2. Use double backslash – This will essentially escape the escape character.

Here's how to use both:

print(r'C:\Users\Bob')
print('C:\\Users\\Bob')
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 5 – Two ways to use backslash inside a string (image by author)

These two apply both for strings surrounded with single and double quotes. We haven't covered double quotes yet, so let's do that next.

What are Double Quotes used for in Python?

It's considered a best practice to use double quotes for natural language messages, string interpolations, and whenever you know there will be single quotes within the string.

Here are a couple of examples:

name = 'Bob'

# Natural language
print("It is easy to get confused with single and double quotes in Python.")

# String interpolation
print(f"{name} said there will be food.")

# No need to escape a character
print("We're going skiing this winter.")

# Quotation inside a string
print("My favorite quote from Die Hard is 'Welcome to the party, pal'")
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 6 – Using double quotes in Python (image by author)

As you can see, we can easily embed quotations into strings surrounded by double quotation marks. Also, there's no need to escape a character as we had to with single quotes.

Keep in mind: you can't use double quotes again in a string surrounded by double quotes. Doing so will result in the same syntax error as with single quotes:

print("You can't use "double quotes" inside this string.")
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 7 – Syntax error when using double quotes inside a double quote string (image by author)

To mitigate, you can reuse the solution from the previous section, but you can also wrap the string in single quotes instead:

print('You can use "double quotes" like this.')
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 8 – Using double quotes in a string (image by author)

Now you know how to use both single and double quotes in Python. We'll recap on the differences and introduce best practices next.

What is the Difference Between Single and Double Quotation Marks in Python?

Here's a summary table answering the question Should you use single or double quotes in Python:

Python Single vs. Double Quotes - Which Should You Use And Why?
Image 9 – Differences between single and double quotes in Python (image by author)

In short, you can use both in all cases, but double quotes are more often used with text and longer strings. There's no one forbidding you to use single quotes everywhere, but you'll have to be more careful, as single quotes are more sensitive to specific characters.

There are some official recommendations from the creators of Python, so let's go over them next.

Python Single vs. Double Quotes PEP8

According to PEP8:

  • PEP doesn't make a recommendation on whether to use single or double quotes – pick a rule and stick to it.
  • When a string is surrounded with single quotes, use double quotes inside it to avoid backslashes.
  • When a string is surrounded with double quotes, use single quotes inside it to avoid backslashes.
  • When using triple quoted strings, always use double quote characters inside it.

We'll go over triple quoted strings and their use cases shortly.

Single vs. Double Quotes Best Practices

Best practices for single quoted strings:

  • Make sure the string is somewhat short, or you're dealing with a string literals
  • Make sure there are no single quotations inside the string, as adding escape characters has a toll on readability.

Best practices for double quoted strings:

  • Use double quotes for text and string interpolation.
  • Use double quotes when there's a quotation inside a string – you can easily surround the quotation with single quotes.

Should You Use Single or Double Quotes in Python?

The ultimate answer is – it depends, mostly on your style preferences. Python doesn't make any difference between single and double quotes, so the decision is up to you.

What you shouldn't do is constantly switch between single and double quotes inside a single Python file or a module. Pick the one you like better and be consistent with it.

Triple Quotes in Python

Yep – there's even a third type of quote in Python. These have their own set of advantages:

  • You can use both single and double quotes inside them.
  • You can split the string into multiple lines.
  • They are considered as a best practice when writing docstrings.

Let's go over a couple of examples:

print("""Triple quote string example 1""")
print('''Triple quote string example 2''')

print("""Here's a string I'll split into
mulitple 
lines.""")

print("""You can use 'single quotes' and "double quotes" inside!""")
Python Single vs. Double Quotes - Which Should You Use And Why?
Image 10 – Triple quotes in Python (image by author)

As you can see, there's no dedicated triple quote character on a keyboard, so we write them using either three single or three double quotes. The biggest advantage is that you can split the string into multiple lines just by pressing Enter, which radically improves the readability.

Still, a primary use case for triple quotes are documentation strings (docstrings) for functions:

def sum_list(lst: list):
    """Iterates over every list element and sums them.
    
    Keyword arguments:
    lst -- the input sequence of numbers.
    """
    res = 0
    for num in lst:
        res += num
        
    return res

You're free to use both ''' and """ to surround a docstring, but the convention is to use the latter.


Conclusion

Long story short – the differences between single and double quoted strings in Python are minimal. You can use either one for anything – just make sure to stick to your programming conventions. There are some use cases when one type has the edge over the other,  but these are few and far between.

Single quoted strings could cause you some trouble if there are quotations inside the string, so keep that in mind. Double quoted strings are a safer bet, but not enough to pick one over the other.

Learn More

Stay connected

To leave a comment for the author, please follow the link and comment on their blog: Python - Better Data Science .

Want to share your content on python-bloggers? click here.