CodeMIRAI
0 XP

Escape characters and raw strings

2 min read 5 runnable examples Quiz included

Some characters are awkward to type inside a string: a quote that matches the string's own quotes, a new line, a tab. Escape sequences solve this. They start with a backslash \.

Common escape sequences

SequenceMeans
\nnew line
\ttab
\\a single backslash
\'single quote
\"double quote
Python
print("Line one\nLine two")
print("Name:\tAsha\nCity:\tMumbai")
print("She said \"hello\"")
print('It\'s easy')
print("C:\\Users\\Asha")

Choosing quotes instead of escaping

Often the simplest fix is to use the other kind of quote:

Python
print("It's easy")              # double quotes around an apostrophe
print('She said "hello"')       # single quotes around double quotes

Raw strings

A raw string has an r before the quote. Backslashes in it are treated as ordinary characters, so nothing is escaped:

Python
print("C:\new_folder")      # \n becomes a new line!
print(r"C:\new_folder")     # raw string: printed as written

Raw strings are essential for Windows paths and for regular expressions, which use lots of backslashes.

Unicode characters

Python strings are Unicode, so you can use any language and emoji directly, or by code:

Python
print("नमस्ते", "こんにちは", "😀")
print("\u2713 done")          # ✓ by its Unicode code point
print(len("😀"))

The end of print

By default, print() ends with \n, which is why each call starts a new line. You met end= earlier; it is the same character:

Python
print("a", end="\n\n")    # one extra blank line
print("b")
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.