Open In App

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.



Escape from single quotes in a string in Python

Wrong way:




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.






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.




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

Output:

Hello I don't dislike python

Escape from double quotes in a string in Python

Wrong way:




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.




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

Output:

He said, "he likes python"

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




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

Output:

He said, "he likes python"

Escape using triple quote

Triple quotes (or docstrings as they are called in official python documentation) can be used to represent multiple strings containing quotes.




print('''
Hello I don't dislike python
He said, "he likes python"
''')

Output:

Hello I don't dislike python
He said, "he likes python"

Using the ‘r’ keyword to specify a raw string

In python, the ‘r’ keyword can be used to indicate a raw string to the compiler. This is rather helpful in special cases like taking input from the user.




# Using single quote
 
print(r"This is '(single quote)'")
 
# Using double quote
 
print(r'This is "(double quote)"')
 
# Using both single and double quote
 
print(r"These are '(single quote)' and " r'"(double quote)"')

Output:

This is '(single quote)'
This is "(double quote)"
These are '(single quote)' and "(double quote)"

Article Tags :