To insert characters that cannot be used directly in a string, you can use an escape character. An example of such a character is a double quote inside a string that is surrounded by double quotes.
print("This will give "error")
Escape sequence characters are represented with a backslash (\
) followed by a specific character or combination of characters.
print("This will run without any \" error")
#output: This will run without any " error
Common Escape Sequences in Python
-
\\
- Backslash: The backslash itself is an escape character, so to print a literal backslash, you need to escape it with another backslash.print("This is a backslash: \\") #output: This is a backslash: \
-
\'
- Single Quote: This allows you to insert a single quote inside a string that is enclosed by single quotes.print('This is a \'single quote\'') #output: This is a 'single quote'
-
\"
- Double Quote: Similar to the single quote escape sequence, this allows you to insert double quotes inside a string that is surrounded by double quotes.print("This is a \"double quote\"") #output: This is a "double quote"
-
\n
- Newline: Inserts a newline, causing the text after it to appear on a new line.print("Line 1\nLine 2") #output: #Line 1 #Line 2
-
\t
- Tab: Inserts a tab space, which is often used for indentation.print("First\tSecond") #output: First Second
-
\\b
- Backspace: Removes the character immediately before it.print("Hello\bWorld") #output: HellWorld
-
\r
- Carriage Return: Moves the cursor back to the beginning of the line.print("Hello\rWorld") # output: World # The \r escape sequence moves the cursor to the beginning of the line, so the text "World" overwrites the text "Hello."