CodeBlanks Logo Icon CodeBlanks

Raw strings

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\Alex

In 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 pattern

Without 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

main.py
# Use a raw string

Sample solution

main.py
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

Question
path = ____"C:\Users\Alex"
Answer
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

All lessons in Beginner