Unit 2 · String Methods
String Methods
Learn Python's built-in string methods to manipulate, format, clean, and search text data.
Learning Objectives
By the end of this lesson, you will be able to:
- Explain why string methods always return a new string.
- Use methods for case conversion (`upper()`, `lower()`, `title()`).
- Clean and validate strings using `strip()`, `isdigit()`, and `isalpha()`.
- Search for substrings using `find()`, `index()`, and `count()`.
- Split a string into a list (`split()`) and join a list into a string (`join()`).
- Differentiate between `find()` and `index()`.
Prerequisites
To fully understand this topic, you should be comfortable with:
- Basic Python strings and the concept of immutability.
- Python lists (for understanding `split()` and `join()`).
Introduction
Python provides a rich library of built-in **string methods** to perform common operations on text. A "method" is a function that is attached to an object. You call it using the syntax `object.method()`.
The Most Important Rule: Immutability
Because strings are **immutable**, string methods **never change the original string**. They always return a **new, modified string**. Forgetting this is a very common mistake for beginners.
Table of Contents
Case Conversion Methods
Convert strings to uppercase, lowercase, or capitalized versions:
text = "hello world" print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.capitalize()) # Hello world (first character capitalized) print(text.title()) # Hello World (each word capitalized)
Search, Count & Validation Methods
Find characters, test for presence, or count occurrences:
phrase = "banana" print(phrase.count("a")) # 3 print(phrase.find("nan")) # 2 (returns index where match begins) print(phrase.find("xyz")) # -1 (returned if match not found)
`find()` vs. `index()` (Key Difference)
Both methods search for a substring and return its starting index. The key difference is how they behave when the substring is **not found**. This is a classic interview question.
| Method | Behavior on Success | Behavior on Failure |
|---|---|---|
| `find()` | Returns the index of the first match. | Returns `-1`. |
| `index()` | Returns the index of the first match. | Raises a `ValueError`. |
When to use which?
Use `find()` when you just want to check for existence without crashing your program. Use `index()` when the substring is expected to be present, and its absence should be treated as an error.
Cleaning and Testing Methods
Strip whitespaces or test character characteristics:
dirty = " clean me " print(dirty.strip()) # "clean me" (removes leading/trailing spaces) code = "12345" print(code.isdigit()) # True (checks if all characters are digits) print(code.isalpha()) # False (checks if all characters are letters)
Split and Join Methods
Transform text to list sequences or join sequences into text:
csv = "red,green,blue" colors = csv.split(",") print(colors) # ['red', 'green', 'blue'] joined = "-".join(colors) print(joined) # red-green-blue
Exam Corner & Practice
Common Mistakes
- Forgetting that string methods return a new string and do not modify the original. (e.g., `my_str.upper()` does nothing on its own; you need `my_str = my_str.upper()`).
- Confusing `find()` (returns -1) with `index()` (raises error).
- Using `split()` and expecting the original string to change.
- Passing the wrong separator to `split()` or `join()`.
Exam Notes
- String methods are essential for data cleaning and preparation.
- `split()` is used to parse structured text (like CSV data) into a list.
- `join()` is used to build a string from a list of strings.
- Methods like `isdigit()`, `isalpha()`, and `isspace()` are useful for input validation.
Interview Questions
- What is the main difference between `find()` and `index()`?
- How would you remove all leading and trailing whitespace from a string? (Answer: `strip()`).
- How do you convert a comma-separated string into a list of items? (Answer: `my_string.split(',')`).
- Why do string methods return a new string instead of modifying the original? (Answer: Because strings are immutable).
Practice Corner
# Question 1: What is the output? text = " Hello World " print(text.strip().upper()) # Answer: "HELLO WORLD" # Question 2: What is the output? items = ["a", "b", "c"] print("-".join(items)) # Answer: "a-b-c"
Summary
Python's built-in string methods provide rich manipulation controls. Because strings are **immutable**, these methods always **return a new string** instead of modifying the original. Key methods include `upper()`/`lower()` for case conversion, `strip()` for cleaning whitespace, `split()`/`join()` for converting between strings and lists, and `find()`/`index()` for searching.