Escape Characters
Escape characters in Python are used to represent special characters in strings. These characters are preceded by a backslash \
to indicate that they have a special meaning.
1. Newline (\n
)
Moves the cursor to the beginning of the next line.
multiline_text = "This is a\nmultiline\nstring."
print(multiline_text)
Output:
This is a
multiline
string.
2. Tab (\t
)
Inserts a horizontal tab.
indented_text = "This is\tindented."
print(indented_text)
Output:
This is indented.
3. Backslash (\\
)
Represents a literal backslash character.
path = "C:\\Users\\John\\Documents"
print(path)
Output:
C:\Users\John\Documents
4. Single Quote (\'
) and Double Quote (\"
)
Allows the inclusion of single and double quotes within a string.
single_quote = 'This is a single quote: \''
double_quote = "This is a double quote: \""
print(single_quote)
print(double_quote)
Output:
This is a single quote: '
This is a double quote: "
5. Backspace (\b
)
Moves the cursor back one space (does not erase characters).
backspace_text = "Hello\b World"
print(backspace_text)
Output:
Hello World
6. Carriage Return (\r
)
Moves the cursor to the beginning of the line (useful for overwriting text).
overwrite_text = "12345\rOverwritten"
print(overwrite_text)
Output:
Overwritten45
7. Unicode Escape (\u
and \U
)
Represents Unicode characters.
unicode_char = "\u03A9" # Represents the Greek letter Omega
print(unicode_char)
Output:
Ω
8. Raw String (r
or R
)
Creates a raw string, disabling the interpretation of escape characters.
raw_text = r"This is a raw\nstring."
print(raw_text)
Output:
This is a raw\nstring.
Escape characters are useful when you need to include special characters in your strings or control the formatting of the output. Understanding and using escape characters correctly is important for writing effective Python code.