How to Escape Quotes in a String in Python
Quotes are fundamental to defining strings in Python and you use either single quotes ('...') or double quotes ("...") to create them. However, when the string itself contains the same type of quote used to delimit it, Python gets confused about where the string ends, resulting in a SyntaxError.
In this guide, you'll learn multiple methods to handle quotes inside strings in Python, with common mistakes shown alongside the correct solutions.
The Problem: Quotes Inside Strings
When a string contains the same type of quote that surrounds it, Python interprets the inner quote as the end of the string:
# ❌ SyntaxError: Python thinks the string ends at "don"
print('I don't like bugs')
Output:
Traceback (most recent call last):
File "<main.py>", line 2
print('I don't like bugs')
^
SyntaxError: unterminated string literal (detected at line 2)
Python sees 'I don' as the string and doesn't know what to do with t like bugs'.
Method 1: Use the Other Quote Type
The simplest solution is to use double quotes to wrap a string containing single quotes, and vice versa:
Single Quotes Inside Double Quotes
print("I don't like bugs")
print("It's a beautiful day")
Output:
I don't like bugs
It's a beautiful day
Double Quotes Inside Single Quotes
print('He said, "Python is great!"')
print('The file is called "data.csv"')
Output:
He said, "Python is great!"
The file is called "data.csv"
This is the most readable and commonly used approach. Choose whichever quote type is not present in your string content:
- String contains
'→ use"..."to wrap it - String contains
"→ use'...'to wrap it
Method 2: Use the Backslash Escape Character (\)
The backslash (\) tells Python to treat the following quote as a literal character, not a string delimiter:
Escaping Single Quotes
print('I don\'t like bugs')
print('It\'s a beautiful day')
Output:
I don't like bugs
It's a beautiful day
Escaping Double Quotes
print("He said, \"Python is great!\"")
print("The variable is called \"name\"")
Output:
He said, "Python is great!"
The variable is called "name"
When Both Quote Types Are Needed
If your string contains both single and double quotes, escaping is necessary for at least one type:
# Escape the single quote
print("She said, \"I don't like bugs\"")
# Or escape the double quotes
print('She said, "I don\'t like bugs"')
Output:
She said, "I don't like bugs"
She said, "I don't like bugs"
Method 3: Use Triple Quotes
Triple quotes ('''...''' or """...""") can contain both single and double quotes without any escaping:
message = """She said, "I don't like bugs" and he agreed."""
print(message)
Output:
She said, "I don't like bugs" and he agreed.
Triple quotes also support multi-line strings:
dialogue = '''
"Hello," she said. "How's it going?"
"I'm fine," he replied. "What's new?"
"Not much," she answered. "Let's grab some coffee."
'''
print(dialogue.strip())
Output:
"Hello," she said. "How's it going?"
"I'm fine," he replied. "What's new?"
"Not much," she answered. "Let's grab some coffee."
Triple quotes are ideal for strings that contain both types of quotes or span multiple lines. They're also used for docstrings in Python functions and classes.
Method 4: Use Raw Strings (r"...")
Raw strings (prefixed with r) treat backslashes as literal characters. They're useful when you need to include backslashes alongside quotes, such as in file paths or regular expressions:
# Regular string: backslash is an escape character
print("Path: C:\\Users\\name")
# Raw string: backslash is literal
print(r"Path: C:\Users\name")
Output:
Path: C:\Users\name
Path: C:\Users\name
For strings with quotes, you can combine raw strings:
print(r"This contains 'single quotes'")
print(r'This contains "double quotes"')
Output:
This contains 'single quotes'
This contains "double quotes"
A raw string cannot end with an odd number of backslashes. This means r"path\" is a SyntaxError. Raw strings also don't help with escaping the same quote type used to delimit the string.
Method 5: Using String Concatenation
For complex cases, you can concatenate strings that use different quote types:
message = "She said, " + '"I don\'t believe it!"'
print(message)
Output:
She said, "I don't believe it!"
Common Escape Sequences Reference
| Escape Sequence | Result |
|---|---|
\' | Single quote (') |
\" | Double quote (") |
\\ | Backslash (\) |
\n | New line |
\t | Tab |
\r | Carriage return |
Practical Examples
Working with JSON Strings
# JSON requires double quotes: use single quotes for the Python string
json_string = '{"name": "Alice", "message": "I\'m here"}'
print(json_string)
Output:
{"name": "Alice", "message": "I'm here"}
Building SQL Queries
# SQL uses single quotes for string values
query = "SELECT * FROM users WHERE name = 'O\\'Brien'"
print(query)
# Cleaner with triple quotes
query = """SELECT * FROM users WHERE name = 'O''Brien'"""
print(query)
HTML Templates
html = '<a href="https://example.com" class="link">Click here</a>'
print(html)
# Or with triple quotes for readability
html = """
<div class="container">
<p>He said, "It's working!"</p>
</div>
"""
print(html.strip())
Output:
<a href="https://example.com" class="link">Click here</a>
<div class="container">
<p>He said, "It's working!"</p>
</div>
Quick Reference: Which Method to Use
| Scenario | Best Method | Example |
|---|---|---|
String contains ' only | Use "..." | "I don't mind" |
String contains " only | Use '...' | 'He said "hello"' |
String contains both ' and " | Triple quotes or escape | """He said, "I don't mind"""" |
| File paths (Windows) | Raw string r"..." | r"C:\Users\name" |
| Multi-line with quotes | Triple quotes | """...""" |
Conclusion
Handling quotes inside Python strings is simple once you know the available options:
- Use the other quote type: the simplest and most readable approach for strings with one type of quote.
- Use the backslash escape (
\): works universally when you need to include the same quote type used to delimit the string. - Use triple quotes: perfect for strings containing both quote types or spanning multiple lines.
- Use raw strings (
r"..."): ideal for file paths and regex patterns where backslashes should be literal.
For everyday code, alternating between single and double quotes based on the string content is the cleanest approach. Reserve backslash escaping and triple quotes for more complex cases.