Strings & string methods
Overview
A string is an immutable sequence of characters. You can access characters by zero-based indexing (`s[0]` for the first, `s[-1]` for the last), loop over them with `for char in s:`, and measure them with `len(s)`. Because strings are immutable, you cannot change a character in place (`s[0] = 'X'` raises a `TypeError`). Instead, you build a new string. Python provides powerful string methods that return new strings: - `s.lower()` / `s.upper()`: Case conversion (great for case-insensitive matching). - `s.strip()`: Removes leading and trailing whitespace. - `s.split(sep)`: Splits the string into a list of strings by the separator (defaults to whitespace). - `sep.join(list_of_strings)`: Joins a list of strings into a single string using `sep` as glue. - `s.count(sub)`: Counts non-overlapping occurrences of a substring. You can also check for substrings easily with the `in` operator (e.g., `'a' in 'banana'`). When you need to build output that mixes variables and text, use f-strings: `f"Hello {name}"`.
Strings are everywhere. From parsing CSV rows to building API URLs, string manipulation is fundamental. In DSA interviews, string problems (like checking for palindromes or counting anagrams) are extremely common and test whether you understand how to efficiently iterate and transform immutable sequences.
Where used: Parsing user input, Formatting log lines, Validating API requests
Why learn this
- You need strings to parse almost any text input.
- String immutability is a frequent interview 'gotcha' — knowing to build a list of chars and `.join()` instead of repeatedly appending to a string saves massive amounts of time (O(N) vs O(N^2)).
Code walkthrough
text = " hello world "
cleaned = text.strip()
words = cleaned.split()
message = "-".join(words)
print(message)
Focus: Notice how each method returns a new string or list. `strip()` removes spaces, `split()` creates a list `['hello', 'world']`, and `join()` glues them with a hyphen.
Aha moment
s = "racecar"
is_palindrome = (s == s[::-1])
print(is_palindrome)
Prediction: What does this output?
Common guess: True
Strings can be sliced exactly like lists. `s[::-1]` creates a reversed copy of the string, making a palindrome check a trivial one-liner.
Common mistakes
- Trying to modify a string in place: `s[0] = 'H'` raises a TypeError. You must build a new string, e.g. `'H' + s[1:]`.
- Forgetting that string methods return new strings: Calling `s.lower()` does not change `s`. You must reassign it: `s = s.lower()`.
- Using .split() wrong: `"a,b,c".split()` (no arguments) splits on whitespace, returning `["a,b,c"]`. You need `"a,b,c".split(",")` to get `["a", "b", "c"]`.
Glossary
- immutable
- An object whose state cannot be changed after creation. In Python, modifying a string always creates a new string.
Recall questions
- What happens if you try to assign `s[0] = 'x'` to a string?
- How do you check if the letter 'z' is in the string `word`?
- Does calling `s.strip()` change the original string `s`?
Understanding checks
What does this code print?
banana
Strings are immutable. `word.upper()` returns a new string `"BANANA"`, but since we don't assign it back to `word`, the original string is unchanged.
Why does this print 1 instead of 3?
Because `.split()` with no arguments splits on whitespace, not commas.
To split by commas, you must explicitly provide the separator: `data.split(',')`.
Practice tasks
Fix the string formatting
The function below should take a name and return a properly capitalized greeting, but it tries to mutate the string in place. Fix it so it returns a new correctly formatted f-string.
Continue learning
Previous: Primitive types: int, float, bool, str
Previous: Lists: indexing, slicing, methods
Next: Slicing lists & strings