Strings in python are enclosed in a single ' ' or double '' '' quotes. Sometimes, we have to use quotes in the same string. Using double quotes in a string that is enclosed within double quotes or using single quotes in a string that is enclosed within single quotes in python gives an error. For example,

print('  'single quotes'  ')

Output

 print(''single quotes'')
            ^
SyntaxError: invalid syntax

In such cases, we can use both(single and double) quotes simultaneously or we can make use of escape sequences.

Printing quotes using both the quotes simultaneously

To print single quotes inside a string the string is enclosed with double-quotes. Similarly, to print double quotes inside a string the string is enclosed with single quotes.

print("'single quotes'")
print('"double quotes"')
print("I'm John")

Output

'single quotes'
"double quotes"
I'm John

Printing quotes using escape sequences

The escape character is a backslash followed by the character which we want to insert in a string. The escape sequence allows us to use double quotes inside a string that is enclosed within double quotes. The escape character for double quotes is represented as \".

Example,

print("This is a statement for \"double quote\". ")

Output

This is a statement for "double quote".

The escape sequence also allows us to use single quotes inside a string which is enclosed within single quotes. The escape character for single quotes is represented as \'.

Example,

print("This is a statement for \'single quote\'.")

Output

This is a statement for 'single quote'.
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions