Definition
An escape character is a backslash followed by a letter, which stands for a special character such as a new line (\n) or a tab (\t). A raw string, written r"...", treats backslashes as ordinary characters.
In simple words
You can't press Enter inside a normal string, so \n means "new line here". If you want a real backslash, as in a Windows path, you either double it or put r in front.
Why it matters
Windows file paths and regular expressions are full of backslashes. Forgetting this is a very common source of confusing errors.
How it works
| Code | Means |
|---|---|
| \n | New line |
| \t | Tab |
| \\ | A backslash |
| \" | A double quote |
| \' | A single quote |
| \u0905 | A Unicode character (अ) |
In code
print("Line one\nLine two")
print("Name:\tRiya")
print("She said \"hello\"")
print("C:\\new\\table")
print(r"C:\new\table")
print(len("\n"), len(r"\n"))Output
Line one Line two Name: Riya She said "hello" C:\new\table C:\new\table 1 2
Common mistakes
- Writing "C:\new\table". \n and \t become a new line and a tab. Use a raw string or forward slashes.
- Ending a raw string with a single backslash: r"C:\" is an error.
Check yourself
Summary
- A backslash starts an escape code.
- Raw strings keep backslashes as they are, which suits paths and regex.
Finished reading?
Sources: The Python Tutorial, python.org