Escape from single quotes in a string in Python

Wrong way:

Python3




print('Hello I don't dislike python')


Output:

    print('Hello I don't dislike python')
                       ^
SyntaxError: invalid syntax

Right way:

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

Python3




print("Hello I don't dislike python")


Output:

Hello I don't dislike python

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

Python3




print('Hello I don\'t dislike python')


Output:

Hello I don't dislike 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