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.
File "example.py", line 1 print('Let's go') ^ SyntaxError: invalid syntax
This issue arises because Python sees the expression in three parts:
To avoid this, you can use double quotes. Or you can escape the single quotation mark as follows:
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.
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.