DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

Escape Characters in Python Strings

Some characters are awkward or impossible to type directly into a string — a newline, a literal quote mark inside a quoted string, a tab. python escape characters solve that problem, and understanding them (along with the closely related python raw string) will save you real confusion the first time you work with file paths or regex patterns full of backslashes.

What Are Escape Characters?

An escape character is a backslash (\) followed by another character, and together they represent something that would otherwise be hard — or impossible — to write directly inside a string.

print("Hello\nWorld")
# Hello
# World

That \n isn't two characters as far as Python's output is concerned — it's a single escape sequence representing one newline character. Without it, you'd have no way to embed a line break directly inside a normal string literal.

Common Escape Sequences

Here's a rundown of the escape sequences you'll actually use, with the output each one produces.

\n — newline
print("Line one\nLine two")
# Line one
# Line two
\t — tab
print("Name:\tAlex")
# Name:    Alex
\ — literal backslash
print("C:\\Users\\Alex")
# C:\Users\Alex

Since a single backslash normally starts an escape sequence, you need two backslashes in a row to represent one literal backslash character in the output.

' and " — quotes inside matching-quote strings
print('It\'s a nice day')
# It's a nice day

print("She said \"hello\"")
# She said "hello"
Less common but useful sequences
print("Column1\bX")   # \b — backspace, moves the cursor back one position before the next character
print("Line1\rLine2")   # \r — carriage return, moves the cursor to the start of the line
print("End\0")           # \0 — null character, sometimes used as a string terminator in low-level contexts

These three show up far less often in everyday code than \n, \t, and \\, but it's worth recognizing them if you ever encounter them in existing code or binary-adjacent data.

Quick reference

Sequence

Meaning

\n

Newline

\t

Tab

\\

Literal backslash

\'

Literal single quote

\"

Literal double quote

\b

Backspace

\r

Carriage return

\0

Null character

Escaping Quotes and Mixing Quote Styles

Escaping a quote that matches the string's own quote style

If a string is wrapped in single quotes and needs to contain an apostrophe, you have to escape it — otherwise Python thinks the string ends early:

text = 'It\'s a nice day'
print(text)   # It's a nice day

The same applies in reverse for double-quoted strings containing a literal ".

The simpler alternative: switch quote styles

Often, the cleanest fix isn't escaping at all — it's just using the other quote character to wrap the string, so the character you need doesn't conflict:

# No escaping needed — double quotes let the apostrophe pass through untouched
text = "It's a nice day"

# No escaping needed — single quotes let the double quote pass through untouched
quote = 'She said "hello"'

This is generally the more readable choice whenever you have the option — reach for escaping mainly when a string genuinely needs both kinds of quotes at once.

Triple-quoted strings for multi-line text

As covered in the earlier strings article, triple-quoted strings ("""...""" or '''...''') let you write multi-line text directly, without needing \n at all:

paragraph = """This spans
multiple lines
naturally, with real line breaks in the source code."""

This is generally more readable than stitching together a single-line string full of \n sequences, especially for longer blocks of text.

Raw Strings: Turning Off Escape Interpretation

The r prefix

Prefixing a string literal with r (or R) tells Python to treat every backslash as a literal character, rather than the start of an escape sequence:

path = r"C:\Users\Alex\Documents"
print(path)   # C:\Users\Alex\Documents — backslashes stay exactly as typed

Compare that to the same string without the r prefix:

path = "C:\Users\Alex\Documents"
print(path)
# Depending on the specific characters, this can silently misinterpret sequences
# like \U or \A as escape codes, producing unexpected output or even an error
Why this matters: Windows file paths and regex

Two situations make raw strings genuinely necessary rather than just convenient:

Windows file paths, which are full of backslashes as path separators:

path = r"C:\Users\name\Documents\file.txt"

Regex patterns, which use backslashes constantly for special character classes:

import re

ph r"\d{3}-\d{3}-\d{4}"
match = re.match(phone_pattern, "555-123-4567")

Without the r prefix, you'd need to double up every single backslash in that pattern ("\\d{3}-\\d{3}-\\d{4}") just to get the literal backslash-d sequence regex actually needs — quickly turning any nontrivial pattern into a hard-to-read mess. Raw strings sidestep that entirely.

A key limitation

Raw strings have one quirky restriction worth knowing: a raw string can't end in an odd number of backslashes, because Python still needs the last backslash to be able to escape the closing quote character if necessary:

path = r"C:\Users\name\"
# SyntaxError — even in a raw string, a trailing single backslash breaks the closing quote

If you genuinely need a string ending in a literal backslash, you'll need to either add an extra backslash (r"C:\Users\name\\" — which actually leaves two literal backslashes at the end) or fall back to a regular, non-raw string with an escaped backslash for just that final character.

5. Practical Tips and Common Mistakes

Combining raw strings with f-strings

You can combine the r prefix with f to get raw-string behavior and variable interpolation in the same string literal — written as rf"..." or fr"..." (both orderings work identically):

folder = "Documents"
path = rf"C:\Users\Alex\{folder}\file.txt"
print(path)   # C:\Users\Alex\Documents\file.txt

This is the cleanest way to build a file path or regex pattern that also needs to embed a variable, without having to choose between raw-string safety and f-string interpolation.

Common beginner mistake: forgetting to escape backslashes in regular strings

The most frequent trip-up here is writing a Windows-style path or regex pattern as a normal string and being surprised when it doesn't behave as expected:

# This looks reasonable, but \U isn't a recognized escape sequence in most contexts,
# and Python may raise a warning or error, or silently produce unexpected results
path = "C:\Users\file.txt"

The fix is either prefixing the string with r, or manually doubling every backslash — the raw-string prefix is almost always the cleaner option.

An alternative: chr() and ord()

For inserting special characters by their underlying Unicode code point, Python's built-in chr() and ord() functions offer another approach, separate from escape sequences entirely:

print(chr(9731))   # ☃ — the Unicode snowman character, by code point
print(ord("A"))     # 65 — the code point for the letter A

This isn't a replacement for everyday escape sequences like \n or \t, but it's a useful tool when you need to insert a specific character that doesn't have its own convenient escape sequence — anything identified purely by its Unicode code point.

PREVIOUSNEXT LESSON