String Methods
In Lesson 1 you created strings; in Lesson 2 you reached inside them. Now you transform them. String methods are built-in operations that produce new strings from existing ones: uppercase, lowercase, stripped of whitespace, split into pieces, or reassembled.
James has a problem. SmartNotes users sometimes paste titles with extra spaces: " My First Note ". He wants to clean them up.
"Call .strip() on the title," Emma says.
James types title.strip() and gets "My First Note". The spaces are gone. But when he prints title again, the original still has spaces.
"That is because strings are immutable," Emma says. "Methods never change the original. They return a new string. If you want to keep the result, assign it: title = title.strip()."
The Core Methods
Here are the string methods you will use most often. Each one returns a new string:
title: str = " My First Note "
title.strip()
title.upper()
title.lower()
Output:
My First Note
MY FIRST NOTE
my first note
Notice that .upper() and .lower() did not remove the spaces. Each method does one thing. .strip() removes leading and trailing whitespace; .upper() converts all characters to uppercase; .lower() converts all characters to lowercase.
Searching and Replacing
title: str = "My First Note"
title.replace("First", "Second")
title.find("First")
title.find("Missing")
title.startswith("My")
Output:
My Second Note
3
-1
True
| Method | What It Does | Returns |
|---|---|---|
.replace(old, new) | Replaces all occurrences of old with new | New string with replacements |
.find(text) | Finds the position where text first appears | Index (int), or -1 if not found |
.startswith(prefix) | Checks if the string begins with prefix | True or False (bool) |
.find() returns -1 when the text is not found. This is different from raising an error. You can use the result to check whether a search succeeded: a value of -1 means "not found."
Splitting and Joining
.split() breaks a string into a list of strings. By default, it splits on whitespace:
sentence: str = "hello world python"
words: list[str] = sentence.split()
Output:
['hello', 'world', 'python']
You can split on a specific separator:
csv_line: str = "python,ai,beginner"
tags: list[str] = csv_line.split(",")
Output:
['python', 'ai', 'beginner']
" ".join() does the reverse. It takes a list of strings and joins them with a separator:
words: list[str] = ["hello", "world"]
sentence: str = " ".join(words)
Output:
hello world
tags: list[str] = ["python", "ai", "beginner"]
tag_line: str = ", ".join(tags)
Output:
python, ai, beginner
The ", ".join(tags) pattern is exactly what the SmartNotes format_tag_list() function will use in the TDG Challenge at the end of this chapter. You are learning the building block now; you will apply it as a specification later.
Immutability: The Key Rule
Strings in Python are immutable: they cannot be changed after creation. Every string method returns a new string. The original is untouched:
title: str = " My First Note "
cleaned: str = title.strip()
title
cleaned
Output:
My First Note
My First Note
title still has the spaces. cleaned is a separate string without them. If you want to update the variable, reassign it:
title: str = " My First Note "
title = title.strip() # now title is "My First Note"
Output:
My First Note
This is the single most important concept in this lesson. When you see string methods in AI-generated code, look for whether the result is assigned to a variable. A bare title.strip() with no assignment does nothing useful.
PRIMM-AI+ Practice: Predicting Method Results
Predict [AI-FREE]
Look at these string method calls. Without running anything, predict the exact result of each one. Write your predictions and a confidence score from 1 to 5 before checking.
text: str = " Hello, World! "
result1: str = text.strip()
result2: str = text.upper()
result3: str = text.replace("World", "Python")
result4: int = text.find("World")
result5: list[str] = "one two three".split()
Check your predictions
result1: "Hello, World!". .strip() removes leading and trailing whitespace only. The space between "Hello," and "World!" stays.
result2: " HELLO, WORLD! ". .upper() converts letters to uppercase but does not touch spaces or punctuation. The leading and trailing spaces remain.
result3: " Hello, Python! ". .replace() swaps "World" for "Python" but does not touch surrounding whitespace.
result4: 9. .find("World") returns the index where "World" starts. Count the characters: 2 spaces + "Hello, " (7 chars) = position 9.
result5: ["one", "two", "three"]. .split() with no argument splits on whitespace.
The tricky one is result4. If you counted positions carefully (remembering the 2 leading spaces), you got it right.
Run
Create a file called method_practice.py with the expressions above. Add print() calls for each one. Run it with uv run python method_practice.py. Compare the output to your predictions.
Investigate
For result4, explain why .find() returns 9 and not 7. (Hint: count the leading spaces.) Write one sentence about how leading whitespace affects .find() results.
Modify
Add text = text.strip() before the other method calls. Predict how result2, result3, and result4 change. Run your modified file to check.
Make [Mastery Gate]
Given a messy title string raw_title: str = " my FIRST note ", write a chain of method calls that produces "My First Note". You may need multiple steps:
- Strip the whitespace
- Convert to a consistent case
- Think about whether Python has a method that capitalizes the first letter of each word (hint: try
.title())
Run uv run python on your file to verify.
Try With AI
If Claude Code is not already running, open your terminal, navigate to your SmartNotes project folder, and type claude. If you need a refresher, Chapter 44 covers the setup.
Prompt 1: Test Your Immutability Understanding
I'm learning Python string methods. Here is my code:
title = " Hello "
title.strip()
print(title)
I expect this to print "Hello" without spaces. Is that
correct? If not, explain what I'm getting wrong.
Read AI's response. Did it explain that .strip() returns a new string and the original title is unchanged? Did it suggest title = title.strip() as the fix? Compare its answer to what you learned about immutability.
What you're learning: You are testing a common misconception (that methods change the original string) and seeing how AI explains the fix. This is the same pattern you will use when debugging your own code.
Prompt 2: Generate a String Cleaning Function
Write a Python function called clean_title that takes a
messy title string (with extra spaces and inconsistent
capitalization) and returns a clean version. Use type
annotations. Show 3 example inputs and outputs as comments.
Read AI's output. Check: does it use .strip() to remove whitespace? Does it handle capitalization? Are the type annotations correct? Does it chain methods or use separate steps? If the approach differs from what you learned, ask AI to explain its choice.
What you're learning: You are reviewing AI-generated code that uses the string methods from this lesson. Evaluating whether AI chose the right methods builds your judgment for larger code reviews.
Key Takeaways
-
String methods return new strings. The original is never changed. Always assign the result:
title = title.strip(). -
Each method does one thing.
.strip()removes whitespace,.upper()changes case,.replace()swaps text. Chain them for multiple transformations. -
.split()and" ".join()convert between strings and lists..split(",")breaks comma-separated text into a list;", ".join(tags)reassembles a list into a string. -
.find()returns -1 when text is not found. This avoids errors. Check the return value before using it as an index.
Looking Ahead
You now know how to create, access, and transform strings. In Lesson 4, you move beyond single values to collections: list[str] for ordered groups, dict[str, int] for key-value pairs, tuple for fixed groups, and set for unique elements. These types let you specify structured data in your function signatures.