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:
Code | Program | Result | Output |
---|---|---|---|
\’ | txt = ‘It\’s alright.’ print(txt) | Single Quote | It’s alright. |
\\ | txt = “This will insert one \ (backslash).” print(txt) | Backslash | This will insert one \ (backslash). |
\n | txt = “Hello\nWorld!” print(txt) | New Line | Hello World! |
\r | txt = “Hello\rWorld!” print(txt) | Carriage Return | Hello World! |
\t | txt = “Hello\tWorld!” print(txt) | Tab | Hello World! |
\b | This example erases one character (backspace): txt = “Hello \bWorld!” print(txt) | Backspace | HelloWorld! |
\f | Form Feed | ||
\ooo | A backslash followed by three integers will result in a octal value: txt = “\110\145\154\154\157” print(txt) | Octal value | Hello |
\xhh | A backslash followed by an ‘x’ and a hex number represents a hex value: txt = “\x48\x65\x6c\x6c\x6f” print(txt) | Hex value | Hello |