August 31, 2018
Difference between single and double quotes in Python
Introduction
In this post, I am going to provide a summary of using quotes in Python. It can be confusing to beginners but it should be easy to grasp by just looking at the following bullet points…
Quotes in Python
- Strings literals in Python must be enclosed with single or double or triple quotes
- It is nice to be consistent but having different types of quotes to enclose strings in the same script should be fine
- If a single quote happens to be part of a string then a double quote can be used to enclose that string. The opposite is also true. We can use a single quote to enclose a string that contains double quotes
- If you want to stick to a specific quote type and don’t want to mix both types, you can still use quotes within a string by using the backslash escape character
- Triple quotes (single or double) can be used to define multiline strings (ex. documentation)
Let us demonstrate that…
Code snippet
If you run the following code snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
print("Welcome to Python") print("Welcome to 'Python'") print("Welcome to \"Python\"") print print('Welcome to Python') print('Welcome to "Python"') print('Welcome to \'Python\'') print print("""Welcome to 'Python'""") print('''Welcome to "Python"''') |
You should get the following output…
1 2 3 4 5 6 7 8 9 10 |
Welcome to Python Welcome to 'Python' Welcome to "Python" Welcome to Python Welcome to "Python" Welcome to 'Python' Welcome to 'Python' Welcome to "Python" |
That is it for today. Thanks for visiting.