Escape Sequence Characters
Escape sequence characters are special characters that we can use inside strings to perform actions like adding a new line or a tab.
Common Escape Sequences
- New Line (
\n): Moves the text following it to a new line. - Tab (
\t): Adds a horizontal tab (usually 4 spaces) to the text. - Backslash (
\\): allows us to include a literal backslash in our string. - Single/Double Quote (
\'or\"): lets us include quotes within a string of the same type.
# New Line example
print("Hello\nWorld")
# Tab example
print("Item 1\tItem 2\tItem 3")
# Quote example
print('It\'s a beautiful day!')
Hello
World
Item 1 Item 2 Item 3
It's a beautiful day!
Why They Are Useful
Escape sequences are especially helpful when we need to format long strings or include characters that normally have a special meaning in Python code.