Saturday, November 23, 2024
Google search engine
HomeLanguagesHow to Escape Quotes From String in 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.

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

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"

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.

Python3




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.

Python3




# 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)"

RELATED ARTICLES

Most Popular

Recent Comments