Raw strings
- Python course
- Beginner
- Lesson 33/116
- 3 min
Learn raw text with r"...".
Raw strings
A raw string ignores escape sequences. Put an r before it:
path = r"C:\Users\Alex"
print(path) # C:\Users\AlexIn a normal string \n becomes a new line; in a raw string \n stays as two characters. This is very handy for file paths and regular expressions.
Raw string uses
Raw strings are most used for file paths and regular expressions. Windows paths have many \:
# Normal: \Users might error
path = r"C:\Users\Alex\file.txt"
pattern = r"\d+" # digit patternWithout a raw string you would write \\ for each \, which is unreadable.
Practice Print a raw string
Assign path = r"C:\Users\Alex". Print print(path).
Starter code
# Use a raw stringSample solution
path = r"C:\Users\Alex"
print(path)Expected output
C:\Users\Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does r"\n" contain?
- A new line character
- An empty string
- It raises an error
- Two characters: \ and n Correct answer
Explanation: In a raw string \n stays as two characters.
2 Complete the raw string
path = ____"C:\Users\Alex"
path = r"C:\Users\Alex"
Explanation: The r prefix makes a raw string.
3 Match the raw string concepts
| Term | Meaning |
|---|---|
r" |
Raw prefix |
\n |
New line (normal) |
r"\n" |
Two characters |
file path |
Common use |