Open In App

How to use quotes inside of a string - Python

Last Updated : 09 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python programming, almost every character has a special meaning. The same goes with double quotes (" ") and single quotes (' '). These are used to define a character or a string. But sometimes there may arise a need to print these quotes in the output. However, the Python interpreter may raise a syntax error. Fortunately, there are various ways to achieve this.

Let us see a simple example of using quotes inside a String in Python.

Python
# single quotes inside double quotes
s = "Hello, 'GeeksforGeeks'"
print(s)

# double quotes inside single quotes
s = 'Hello, "GeeksforGeeks"'
print(s)

Output
Hello, 'GeeksforGeeks'
Hello, "GeeksforGeeks"

Now let’s explore other different methods to use quotes inside a String.

Using Escape Sequence

Python escape sequence are used to add some special characters in to the String. One of these characters is quotes, single or double. This can be done using the backslash (\) before the quotation characters.

Python
# escape sequence with double quotes
s = "Hello, \"GeeksforGeeks\""
print(s)

# escape sequence with single quotes
s = 'Hello, \'GeeksforGeeks\''
print(s)

# escape sequence with both single and double quotes
s = "Hello, \"GeeksforGeeks\" and \'hey Geeks'"
print(s)

Output
Hello, "GeeksforGeeks"
Hello, 'GeeksforGeeks'
Hello, "GeeksforGeeks" and 'hey Geeks'

Using Triple Quotes

triple quotes (""" or ''') in Python work as a pre-formatted block. This also follows alternative quote usage, i.e., if double quotes are used to enclose the whole string, then direct speech should be in single quotes and vise-versa.

Python
# single quotes inside triple double quotes
s = """Hello, 'GeeksforGeeks'"""
print(s)

# double quotes inside triple single quotes
s = '''Hello, "GeeksforGeeks"'''
print(s)

s = '''Hello, "GeeksforGeeks" And Hey Geeks'''
print(s)

Output
Hello, 'GeeksforGeeks'
Hello, "GeeksforGeeks"
Hello, "GeeksforGeeks" And Hey Geeks

Next Article
Practice Tags :

Similar Reads