Python Single Quote vs Double Quote

You can use Python single quotes and double quotes to create strings. There is no difference between the two. It does not matter which approach you use.

print("This is fine")
print('Just like this')

Regardless of which one you use, please be consistent with it in the codebase. Do not write one string with double quotes and the other with singles.

Also, there are a couple of things to keep in mind when dealing with strings in Python. Let’s briefly discuss them.

The Problem with Quotation Marks inside a String

If you use words like let's in a string with single quotes, you need to handle the misinterpretation by Python.

For example, this string is erroneous:

print('Let's go')

Output:

  File "example.py", line 1
    print('Let's go')
               ^
SyntaxError: invalid syntax

This issue arises because Python sees the string in three parts instead of a single string. Here’s what the Python interpreter sees:

  1. 'Let'
  2. s go
  3. '

Naturally, this is not going to work.

To avoid strings causing errors like this, you can use double quotes.

print("Let's go")

Output:

Let's go

Or you can escape the single quotation mark with a backslash as follows:

print('Let\'s go')

Output:

Let's go

The \’ tells the Python interpreter you want to escape the ‘ character. In other words, you tell the interpreter that this character that normally would terminate the string is now part of it and should be ignored by the interpreters.

Read more about how to quote a Python string.

How About Triple Quote in Python

If you are more familiar with Python, you may know there is also a special type of string that is created with a triple quote ”’ … ”’.

This is known as a docstring. It can be used to document functions, classes, modules, and types.

For example, a docstring could look like this:

def add(a, b):
    """ sums up two numbers """
    return a + b

The docstring works in conjunction with the help() function in Python. When you call help() on an object, it returns the docstring of the object (if any).

It is possible to use a docstring to solve the problem of quotes inside strings. But you should not do it because they are intended to document code. Not to write strings.

Read more about docstrings in Python.

Conclusion

In Python, you can create a string with double quotation marks or single quotation marks. There is no difference.

When using quotation marks inside a string, make sure to escape them not to cause syntax errors.

A triple quotation mark in the string is used as a documentation string. Do not use it as a regular string.

Thanks for reading. I hope you enjoy it!

Happy coding!

Further Reading