Strings & string methods

RoadmapsPython

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

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

Glossary

immutable
An object whose state cannot be changed after creation. In Python, modifying a string always creates a new string.

Recall questions

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

Return to Python Roadmap