Python Single Quote vs Double Quote

Python single quotes vs double quotes

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:

print('Let's go')

Output:

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

This issue arises because Python sees the expression in three parts:

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

To avoid this, you can use double quotes. Or you can escape the single quotation mark as follows:

print('Let\'s go')

Output:

Let's go

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

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

Today you learned what is the difference between Python single quotes and double quotes.

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

Python Interview Questions and Answers

Useful Advanced Features of Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.