Escape Characters
Use backslash escapes to include special characters in strings.
Syntax
'line1\nline2'
r'C:\path'Some characters cannot be typed directly inside a string, so you use an escape sequence that starts with a backslash \.
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\' | Single quote |
\\ | Backslash |
A raw string r'...' turns escapes off, which is handy for file paths and regular expressions.
Example
print('Line 1\nLine 2')
print('Name:\tAda')
print('It\'s fine')
print(r'C:\new\folder')
# Output:
# Line 1
# Line 2
# Name: Ada
# It's fine
# C:\new\folderWhen to use it
- A file path builder on Windows uses \\n to avoid accidental newlines in path strings.
- A text file writer embeds newline \n and tab \t characters to structure output.
- A JSON serialiser ensures double quotes inside string values are escaped to produce valid JSON.
More examples
Newline and tab escapes
Uses \n for a newline and \t for a tab character inside a regular string literal.
print('Line 1\nLine 2\nLine 3')
print('Name:\tAlice')
# Output:
# Line 1
# Line 2
# Line 3
# Name: AliceEscaping quotes
Escapes double and single quotes inside strings that use the same quote character as the delimiter.
msg1 = "She said \"hello\" to me."
msg2 = 'It\'s a great day!'
print(msg1)
print(msg2)
# Output:
# She said "hello" to me.
# It's a great day!Raw strings for file paths
Prefixing with r creates a raw string where backslashes are treated as literal characters.
# Without raw string, \Users would be interpreted:
path = r'C:\Users\Ada\Documents\report.txt'
print(path)
# Output:
# C:\Users\Ada\Documents\report.txt
Discussion