8.5 Escape Characters

By | September 29, 2021

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Example

You will get an error if you use double quotes inside a string that is surrounded by double quotes:
txt = “We are the so-called “Vikings” from the north.”

Output:
  File “demo_string_escape_error.py”, line 1
    txt = “We are the so-called “Vikings” from the north.”
                                       ^
SyntaxError: invalid syntax

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:
txt = “We are the so-called \”Vikings\” from the north.”

Output:
We are the so-called “Vikings” from the north.

Escape Characters

Other escape characters used in Python:

CodeProgramResultOutput
\’txt = ‘It\’s alright.’
print(txt)
Single QuoteIt’s alright.
\\txt = “This will insert one \ (backslash).”
print(txt)
BackslashThis will insert one \ (backslash).
\ntxt = “Hello\nWorld!”
print(txt)
New LineHello
World!
\rtxt = “Hello\rWorld!”
print(txt)
Carriage ReturnHello
World!
\ttxt = “Hello\tWorld!”
print(txt)
TabHello   World!
\bThis example erases one character (backspace):
txt = “Hello \bWorld!”
print(txt)
BackspaceHelloWorld!
\fForm Feed
\oooA backslash followed by three integers will result in a octal value:
txt = “\110\145\154\154\157”
print(txt)
Octal value

Hello
\xhhA backslash followed by an ‘x’ and a hex number represents a hex value:
txt = “\x48\x65\x6c\x6c\x6f”
print(txt)
Hex valueHello

Leave a Reply

Your email address will not be published. Required fields are marked *