Escape from double quotes in a string in Python

Wrong way:

Python3




print("He said, "he likes python"")


Output:

    print("He said, "he likes python"")
                      ^
SyntaxError: invalid syntax

Right way:

Instead of using double quotations, enclose the string in single quotes.

Python3




print('He said, "he likes python"')


Output:

He said, "he likes python"

Before the double quotation in the string, insert the escape character.

Python3




print("He said, \"he likes python\"")


Output:

He said, "he likes python"

How to Escape Quotes From String in Python

The single or double quotation is a unique character that can be used in a Python program to represent a string by encapsulating it in matching quotes. When the quotes are used inside a string contained in similar quotes it confuses the compiler and as a result, an error is thrown. 

This article will demonstrate how to escape quotes from a string in Python.

Similar Reads

Escape from single quotes in a string in Python

Wrong way:...

Escape from double quotes in a string in Python

...

Escape using triple quote

...

Using the ‘r’ keyword to specify a raw string

...

Contact Us