Skip to Content
Course content

24: Escape Sequences and Raw Strings

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You'll eventually run into a situation where you need to put a character inside a string that Python normally uses for something else. The most common culprit is the backslash (\). In Python, the backslash is a "special" character—it's the signal that an escape sequence is starting. If you've ever tried to print a Windows file path and suddenly found your text jumping to a new line or throwing a syntax error, you've hit this wall.

The Backslash Surprise

Imagine you're writing a script to move some logs, and you define your path like this:

path = "C:\users\name\new_project\logs.txt"

At first glance, it looks perfect. But when you print that variable, you'll see something weird. The \n in \new_project isn't treated as a literal "backslash n"; Python sees it as the escape sequence for a newline. Your path just got split across two lines, and your program is now looking for a folder that doesn't exist. This is the "naive" way—assuming the string is just a sequence of characters. In reality, Python is scanning that string for shortcuts like \n (newline), \t (tab), or \" (a literal double quote).

Escaping Your Way Out

The immediate fix is to "escape the escape character." If you want a literal backslash, you have to use two of them. It tells Python, "I know the first backslash is a signal, but I actually want the character that follows it."

path = "C:\\users\\name\\new_project\\logs.txt"

This works perfectly, and it's the standard way to handle occasional special characters. If you need to put a quote inside a string that's already wrapped in double quotes, you'd do the same: "He said, \"Python is great.\"". But let's be honest: if you're dealing with a long Windows path or a complex Regular Expression (regex) string, your code starts to look like a fence made of backslashes. It's noisy, it's hard to read, and it's incredibly easy to miss one, which leads to bugs that are a pain to track down.

When the Backslash Becomes a Burden

When you find yourself typing \\\\ just to get two backslashes in a string, you've reached the point where you should stop fighting the language and use a raw string. By prefixing your string literal with an r, you tell Python to ignore all escape sequences. The backslash just becomes a regular character.

path = r"C:\users\name\new_project\logs.txt"

Now the string is exactly what it looks like. I almost always use raw strings for regex patterns and OS paths because it removes the cognitive load. You don't have to stop and think, "Wait, does \b mean a backspace here or is it part of my folder name?"

There is one quirky trade-off to keep in mind: a raw string cannot end with an odd number of backslashes. Because the \" at the end of a raw string still tells Python to escape the closing quote, r"C:\" will throw a syntax error. If you absolutely must have a backslash at the very end, you'll have to go back to the doubled-backslash method or concatenate a single backslash at the end. It's a weird edge case, but it's the price we pay for the convenience of raw strings.




📋 Practical Task

Fixing the Broken Windows Path Formatter

You have been handed a piece of code that is supposed to generate a list of configuration file paths, but it's currently broken because of how Python handles escape sequences. The output is currently mangling the folder names (specifically those starting with 'n' or 't').

Your Task: Modify the paths list below so that the strings are printed exactly as they are written, without any unexpected newlines or tabs. Use raw strings to fix the issue, as this is the cleanest approach for system paths.

# BROKEN CODE
paths = [
    "C:\temp\settings.ini", 
    "C:\new_folder\config.json", 
    "C:\test_data\logs.txt"
]

for p in paths:
    print(p)

# EXPECTED OUTPUT:
# C:\temp\settings.ini
# C:\new_folder\config.json
# C:\test_data\logs.txt
Rating
0 0

There are no comments for now.

to be the first to leave a comment.