Lesson 3: Strings — Slicing, Methods & f-Strings
String indexing and slicing, powerful string methods, and modern formatted strings.
What is a String?
A string is a sequence of characters — letters, digits, spaces, symbols. You create one with single quotes, double quotes, or triple quotes:
single = 'hello'
double = "hello"
multi = """multi-line
string"""
Strings are immutable: once created, you cannot change a string in place. Any operation that "changes" a string actually creates a brand-new one.
Why Strings Are the Most-Used Type
Every piece of text a program touches is a string: names, emails, messages, JSON payloads, file paths, API responses, log lines. Data cleaning, web scraping, and natural-language processing are almost entirely string gymnastics. Master strings and you master the majority of everyday programming.
What You'll Learn in This Lesson
- Index and slice strings with positive and negative indexes
- Use the most important string methods
- Master f-strings — the modern, professional way to format text
- Understand why strings are immutable
- Escape characters and work with multi-line text
Indexing — Grabbing One Character
Every character in a string has a position (an index), counting from 0:
Index: 0 1 2 3 4
Value: A m o l s
-5 -4 -3 -2 -1 <- negative indexes
name[0]→ first charactername[4]→ fifth charactername[-1]→ last character (negative indexes count from the end)name[-2]→ second-to-last character
Trying to access an index that does not exist raises IndexError: string index out of range.
Mental model: index numbers sit between characters for slicing, but on characters for indexing. Index
0is the first character, and-1is the last — they meet in the middle.
Slicing — Grabbing a Range
A slice extracts a range of characters using the syntax start:end — and the end is exclusive (it stops just before end):
| Slice | Meaning | name = "Amol Shukla" |
|---|---|---|
name[0:4] |
chars 0,1,2,3 | "Amol" |
name[5:] |
from index 5 to the end | "Shukla" |
name[:4] |
from the start to index 4 | "Amol" |
name[:] |
the whole string | "Amol Shukla" |
name[::2] |
every 2nd character | "AoSkl" |
name[::-1] |
reversed | "alkuhS lomA" |
The full slice syntax is start:stop:step. Leave any part blank to use the default (start = 0, stop = end, step = 1).
Fence-post rule: a slice
s[1:4]includes posts 1, 2, and 3 but stops before post 4.
Classic slice recipes:
s[::-1]— reverse any string (the most popular slice in existence).s[:len(s)//2]— first half;s[len(s)//2:]— second half.s[-3:]— last three characters (e.g., grabbing a file extension:"report.pdf"[-3:]→"pdf").
Escape Characters — Special Text
Some characters need a backslash to be written inside a string:
| Escape | Meaning | Example |
|---|---|---|
\n |
Newline | "line1\nline2" |
\t |
Tab | "col1\tcol2" |
\\ |
A literal backslash | "C:\\Users" |
\" |
A quote inside double quotes | "He said \"hi\"" |
\' |
A quote inside single quotes | 'It\'s fine' |
For raw text (like Windows paths or regex), prefix with r: r"C:\Users\Amol" keeps every backslash literally.
String Methods — Built-in Superpowers
Strings ship with dozens of methods. The most important ones:
| Method | What it does | Example → Result |
|---|---|---|
.upper() |
All uppercase | "hi".upper() → "HI" |
.lower() |
All lowercase | "HI".lower() → "hi" |
.strip() |
Remove surrounding whitespace | " hi ".strip() → "hi" |
.split() |
Split into a list | "a b c".split() → ["a", "b", "c"] |
.replace(a, b) |
Swap text | "a-b".replace("-", "_") → "a_b" |
.startswith(x) |
Starts with x? | "py".startswith("p") → True |
.endswith(x) |
Ends with x? | "py".endswith("y") → True |
.find(x) |
Index of first x | "abc".find("b") → 1 |
.count(x) |
How many times x appears | "aaa".count("a") → 3 |
.join(list) |
Glue a list into a string | "-".join(["a", "b"]) → "a-b" |
.capitalize() |
First letter uppercase | "python".capitalize() → "Python" |
.title() |
Every word capitalized | "hello world".title() → "Hello World" |
.isdigit() |
All characters digits? | "42".isdigit() → True |
.isalpha() |
All characters letters? | "abc".isalpha() → True |
Because strings are immutable, every method returns a new string — the original is untouched. You can chain methods:
email = " Amol@Example.COM "
clean = email.strip().lower()
# "amol@example.com"
.split() and .join() are the two most-used methods in data work:
sentence = "Python,is,awesome"
parts = sentence.split(",") # ['Python', 'is', 'awesome']
glued = " ".join(parts) # 'Python is awesome'
Mental model:
.split()chops a string into a list at a delimiter;.join()is the exact reverse — it welds a list back together with a glue string.
f-Strings — The Modern Way to Format
f-strings (formatted strings) embed expressions directly inside text using curly braces:
course = "Python"
lessons = 25
print(f"Welcome to {course} — {lessons} lessons!")
# Welcome to Python — 25 lessons!
You can even run expressions and format numbers inside the braces:
price = 9.567
print(f"Price: {price:.2f}") # Price: 9.57
print(f"Sum: {2 + 3}") # Sum: 5
Format specifiers (after the colon) give precise control:
| Specifier | Meaning | Example → Result |
|---|---|---|
:.2f |
2 decimal places | f"{3.14159:.2f}" → "3.14" |
:,.2f |
Thousands separator + decimals | f"{1234567.5:,.2f}" → "1,234,567.50" |
:>10 |
Right-align in 10 chars | f"{'hi':>10}" → " hi" |
:^10 |
Center in 10 chars | f"{'hi':^10}" → " hi " |
:.0% |
Percentage | f"{0.85:.0%}" → "85%" |
:08d |
Zero-pad to 8 digits | f"{42:08d}" → "00000042" |
These turn ugly numeric output into polished reports — essential for the data tables you will build later in the course.
f-strings vs the Old Ways
| Method | Example | Verdict |
|---|---|---|
+ concatenation |
"Hi " + name + "!" |
Clunky, error-prone |
.format() |
"Hi {}".format(name) |
Fine, but verbose |
| f-string | f"Hi {name}!" |
Fast, clean, modern |
Professional Python code in 2026 uses f-strings almost exclusively.
Common Mistakes to Avoid
- Mistake:
name[5]when the string has only 5 characters — Fix: remember indexes start at 0; the last valid index islen(name) - 1. - Mistake: Expecting
"Hello".upper()to change"Hello"— Fix: methods return new strings; assign the result:text = text.upper(). - Mistake:
"count: " + 5— Fix: use an f-string:f"count: {5}". - Mistake: Slicing with the end index included — Fix:
s[0:4]gives characters 0–3, not 0–4. - Mistake: Forgetting
\nvs\n— Fix: user"..."raw strings for paths and regex. - Mistake: Using
.replace()and expecting the original to change — Fix: assign the result back.
Professional Tips & Tricks
- f-strings beat + concatenation: faster, safer, and readable.
- Chain methods:
email.strip().lower().replace(' ', '_'). - Use
.split()to turn messy text into clean lists — the basis of data cleaning. - Use
.join()to build strings from lists — it is faster and cleaner than repeated+. - Check
.isdigit()before casting user input to avoidValueError.
Key Takeaways
- Strings are immutable sequences of characters with 0-based indexes.
- Negative indexes count from the end;
[::-1]reverses a string. - String methods return new strings — assign the result.
- f-strings with
{...}are the professional formatting standard. - Slicing works identically on lists and tuples (Lesson 8).
.split()and.join()are the power pair for text processing.
Next up: Operators & expressions — how Python does math and logic.
# String indexing, slicing, methods and f-strings
name = "Amol Shukla"
# Indexing (first and last characters)
print("First char:", name[0])
print("Last char:", name[-1])
# Slicing (first name = 0:4)
print("First name:", name[0:4])
print("Surname:", name[5:])
# Methods return NEW strings
email = " Amol@Example.COM "
print("Cleaned:", email.strip().lower())
print("Words:", email.strip().split("@"))
# f-strings
course = "Python"
lessons = 25
print(f"Welcome to {course} — {lessons} lessons!")Lesson Code (Python)
# String indexing, slicing, methods and f-strings
name = "Amol Shukla"
# Indexing (first and last characters)
print("First char:", name[0])
print("Last char:", name[-1])
# Slicing (first name = 0:4)
print("First name:", name[0:4])
print("Surname:", name[5:])
# Methods return NEW strings
email = " Amol@Example.COM "
print("Cleaned:", email.strip().lower())
print("Words:", email.strip().split("@"))
# f-strings
course = "Python"
lessons = 25
print(f"Welcome to {course} — {lessons} lessons!")Console Output
First char: A
Last char: a
First name: Amol
Surname: Shukla
Cleaned: amol@example.com
Words: ['Amol', 'example.COM']
Welcome to Python — 25 lessons!Code Visualization Tips
- Draw a string as a row of numbered boxes (0,1,2...) and point at each box with your finger while indexing.
- For slices, remember the fence-post rule: s[1:4] includes posts 1,2,3 but stops before post 4.
- Use the interactive REPL to try name[::2] and see every second character — slicing with steps.
Professional Tips & Tricks
- f-strings beat + concatenation: faster, safer, and readable.
- Chain methods: email.strip().lower().replace(' ', '_')
- Use .split() to turn messy text into clean lists — the basis of data cleaning.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Email & Domain Extractor
Test Your Knowledge
Instant feedbackQuick Check: Lesson 3: Strings & String Methods Mastery
Up next · Continue learning
Operators & Expressions
Arithmetic, comparison, logical, and assignment operators — plus expression evaluation order.