Python Single vs Double Quotes: Which Should You Use
To create a string in Python, you can use either single or double-quotes. Nevertheless, in specific circumstances, the type of quotes can matter, depending on the content of the string itself. In Python, use a double quote for text, a Single quote for anything that behaves like an identifier, Double quoted raw string literals for regular expressions, and triple quotes for docstrings.
Python Single vs Double Quotes
There is no single suggested way provided by PEP 8 on where and when to use Single Quotes and Double Quotes in Python. But the community is following a standard way in which you can use Single quotes in certain scenarios, double quotes in other, and triple quotes in other cases.
- Use double quotes when strings that are used for interpolation or that are natural language messages.
- Use a single quote for small symbol-like strings but be careful when strings already contain quotes. It would be a good idea if you escaped those in-string quotes.
- Use triple double-quotes for docstrings and raw string literals for regular expressions, even if needed.
Whichever quote you choose, be consistent with your method throughout your project.
There are some exceptions like if the string you have contains one, you should use the other. For example, “You’re having a great day”, or ‘She said “Hi!”‘. Other than that, you should be as consistent as you can.
data = "He's doing a fantastic job!" print(data) data2 = 'Playstation 5' print(data2) """ Oh My God """
He's doing a fantastic job! Playstation 5
From the output, you can see that there is no difference. Instead, people will tell you to choose whichever style matches the context and to be consistent.
Escaping a String in Python
To escape a string in Python, use the forward-slash(\) operator.
info = 'You\'re a pro gamer' print(info)
You're a pro gamer
You can see that we started a string with a single quote, and inside the string, there is another single quote at ‘re. So, it will create confusion for Python, and to remove that, we need to add forward slash operator(\) to escape it, and then we can continue our sentence.
You can escape it with double quotes, too, with the same forward slash operator.
That is it for Python Single vs Double Quotes Tutorial.