String Methods and Formatting¶
By the end of this lesson you'll be able to:
- Access individual characters using string indexing and extract substrings using slicing
- Use
split(),join(),replace(),find(),startswith(), andendswith()to work with text - Build clean output strings using f-strings — the modern Python way to embed variables in text
- Format multiline output to make your programs look professional
Strings are everywhere in programming. Usernames, messages, file names, web addresses — all text. Python gives you a huge toolkit of string methods so you can chop, search, replace, and format text with just a few lines of code.
Welcome to Chapter 14!
Strings are one of the most useful tools in your Python toolbox!
Today you'll learn how to slice them, search them, replace parts, and format beautiful output.
Let's code it together!
String Indexing¶
Every character in a string has a position number called an index.
Python starts counting at zero — so the first character is at index 0, the second at 1, and so on.
You access a character using square brackets: word[index].
1 2 3 | |
You can also count backwards from the end using negative numbers:
1 2 3 | |
String Slicing¶
Slicing extracts a portion (a "slice") of a string.
The syntax is word[start:end] — it gives you characters from start up to (but NOT including) end.
1 2 3 4 5 6 | |
What Do You Think Will Happen?
Before running the code below, predict what "programming"[3:8] will print.
Count the characters starting at index 0. Make your guess — then run it!
Were you right? s[3:8] gives you "gramm" — characters at positions 3, 4, 5, 6, and 7.
The ::2 notation is a step — s[::2] takes every second character.
See It: Slice with Your Hands¶
The slicer below turns slice notation into something you can grab. Drag the green start handle and the red end handle and watch the word[2:7] notation update live. Before you drag anything, predict: where do the two handles need to sit to extract "ROCKS"?
Explore the String Slicer MicroSim
Notice that the red end handle always sits one position past the last selected letter — the end index is never included. Click any single tile to see plain indexing like word[3], type your own word, or click New Challenge to practice.
Split, Join, and Replace¶
Three of the most-used string methods are split(), join(), and replace().
Before looking at examples, here's a quick preview:
- split() breaks a string into a list of pieces
- join() glues a list of strings back together
- replace() swaps every occurrence of one substring for another
| Method | What it does | Example |
|---|---|---|
s.split() |
Split on spaces | "a b c".split() → ["a","b","c"] |
s.split(",") |
Split on commas | "a,b,c".split(",") → ["a","b","c"] |
"-".join(lst) |
Join with dashes | "-".join(["a","b"]) → "a-b" |
s.replace("x","y") |
Replace x with y | "fox".replace("x","t") → "fot" |
Searching Strings¶
Python gives you several methods to search inside a string:
s.find("x")— returns the index of the first occurrence of"x", or-1if not founds.startswith("x")— returnsTrueif the string starts with"x"s.endswith("x")— returnsTrueif the string ends with"x"s.isdigit()— returnsTrueif all characters are digits (no letters, no spaces)s.isalpha()— returnsTrueif all characters are letterss.isalnum()— returnsTrueif all characters are letters or digits
f-Strings — The Modern Way to Format Text¶
An f-string (formatted string literal) lets you embed variables directly inside a string.
Put an f before the opening quote and wrap each variable in curly braces {}.
Before f-strings, you had to write things like:
1 2 3 | |
With an f-string, that becomes much cleaner:
1 | |
The :.1f format code inside the curly braces says "show 1 decimal place."
Try changing it to :.2f for two decimal places.
String Comparison¶
You can compare strings with ==, <, and >.
Python compares strings alphabetically, character by character.
1 2 3 4 | |
Case matters! "apple" != "Apple". Use .lower() on both sides if you want case-insensitive comparison.
Multiline String Formatting¶
You can create a string that spans multiple lines using triple quotes """...""".
This is perfect for longer messages or templates:
1 2 3 4 5 6 7 8 9 10 11 | |
Learning Check¶
Your Turn — Fix the Greeting
The program below should print a polished greeting using an f-string,
but it still uses the old + concatenation style and forgets str() around the number.
Rewrite the print() line as a single f-string to fix both problems!
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Try
"Python"[::-1]— that's a slice with step-1. You'll know it worked when you seenohtyP(the string reversed!). -
Use
split(",")to split the string"red,green,blue,yellow"and print each color on its own line. You'll know it worked when you see four lines, one color each. -
Use
replace()to censor the word"bad"in"This is a bad example", replacing it with"***". You'll know it worked when the output readsThis is a *** example. -
Write an f-string that displays a pizza order: ingredient (e.g.
"cheese") and price (e.g.8.50) with two decimal places. You'll know it worked when you see something likePizza: cheese — $8.50. -
Use
startswith()to check if a filename ends with".py". Print"Python file!"or"Not a Python file". You'll know it worked when"hello.py"gives one result and"hello.txt"gives the other.
String Master!
You've learned indexing, slicing, split, join, replace, f-strings, and more!
These string skills appear in almost every real Python program — from web apps to data science.
You're building a seriously impressive toolkit! Let's keep coding!