Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do we use double quotation in Python?
Double quotes in Python are used to create string literals, just like single quotes. Both have identical functionality, allowing you to choose based on readability and the content of your string.
Basic Syntax
The syntax for creating a string using double quotes is straightforward ?
text = "Hello, World!" print(text) print(type(text))
Hello, World! <class 'str'>
Using Single Quotes Inside Double Quotes
Double quotes allow you to include single quotes without escaping ?
message = "It's a beautiful day!" quote = "She said, 'Hello there!'" print(message) print(quote)
It's a beautiful day! She said, 'Hello there!'
Mixing Single and Double Quotes
When using the same quote type inside a string, you need escape characters (\) ?
# Using escape character for double quotes inside double quotes text1 = "He said, "Python is awesome!"" print(text1) # Alternative: use single quotes to wrap double quotes text2 = 'He said, "Python is awesome!"' print(text2)
He said, "Python is awesome!" He said, "Python is awesome!"
Handling Escape Characters
Escape characters like \n and \t have special meanings. Use raw strings (prefix with r) to treat backslashes literally ?
# Regular string with escape characters
path1 = "C:\docs\new_file.txt"
print("Regular string:")
print(path1)
# Raw string treats backslashes literally
path2 = r"C:\docs\new_file.txt"
print("\nRaw string:")
print(path2)
Regular string: C:\docs ew_file.txt Raw string: C:\docs\new_file.txt
When to Use Double Quotes
Choose double quotes when your string contains single quotes or apostrophes ?
# Better readability with double quotes
contractions = ["don't", "can't", "won't", "it's"]
for word in contractions:
sentence = f"The word '{word}' is a contraction."
print(sentence)
The word 'don't' is a contraction. The word 'can't' is a contraction. The word 'won't' is a contraction. The word 'it's' is a contraction.
Comparison
| Scenario | Recommended Quote | Example |
|---|---|---|
| Contains apostrophes | Double quotes | "It's working" |
| Contains speech | Single quotes | 'He said "Hello"' |
| File paths | Raw strings | r"C:\folder\file.txt" |
Conclusion
Double quotes in Python create strings identically to single quotes. Use double quotes when your string contains apostrophes for better readability, and remember to use raw strings for file paths containing backslashes.
