Escape sequences allow you to include special characters in strings. To do this, simply add a backslash (
\) before the character you want to escape.
For example, imagine you initialized a string with single quotes:
s = 'Hey, whats up?' print(s)
Hey, whats up?
But if you include an apostrophe without escaping it, then you will get an error:
s = 'Hey, what's up?' print(s)
File "main.py", line 1 s = 'Hey, what's up?' ^ SyntaxError: invalid syntax
To fix this, just escape the apostrophe:
s = 'Hey, what\'s up?' print(s)
To add newlines to your string, use
print("Multiline strings\ncan be created\nusing escape sequences.")
Multiline strings can be created using escape sequences.
An important thing to remember is that, if you want to include a backslash character in a string, you will need to escape that. For example, if you want to print a directory path in Windows, you'll need to escape each backslash in the string:
A raw string can be used by prefixing the string with
R, which allows for backslashes to be included without the need to escape them. For example:
print(r"Backslashes \ don't need to be escaped in raw strings.")
Backslashes \ don't need to be escaped in raw strings.
But keep in mind that unescaped backslashes at the end of a raw string will cause and error:
print(r"There's an unescaped backslash at the end of this string\")
File "main.py", line 1 print(r"There's an unescaped backslash at the end of this string\") ^ SyntaxError: EOL while scanning string literal
Common escape sequences
|'||Single quote (
|"||Double quote (
|\n||ASCII Linefeed (adds newline)|
A full list of escape sequences can be found here in the Python docs.