Skip to content

How to Escape Quotes in a String in Python

Learn how to properly handle quotes inside Python strings using different methods like switching quote types, escape characters, triple quotes, and raw strings to avoid SyntaxError.

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:

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)

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"

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:

print("She said, \"I don't like bugs\"")

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."

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:

print("Path: C:\\Users\\name")

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"

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_string = '{"name": "Alice", "message": "I\'m here"}'
print(json_string)

Output:

{"name": "Alice", "message": "I'm here"}

Building SQL Queries

query = "SELECT * FROM users WHERE name = 'O\\'Brien'"
print(query)

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)

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.

Navigation