9.7 Common String Methods
The str type's built-in method set grouped by purpose -- case conversion, searching, validation, modification, splitting/joining, alignment, encoding, and translation.
Every method below returns a new string (or list/tuple) — none modify the original, consistent with 9.1 Introduction to Strings.
Case Conversion
| Method | Example | Result |
|---|---|---|
upper() | "Hello".upper() | 'HELLO' |
lower() | "Hello".lower() | 'hello' |
capitalize() | "hello".capitalize() | 'Hello' |
title() | "hello world".title() | 'Hello World' |
swapcase() | "Hello".swapcase() | 'hELLO' |
casefold() | "STRASSE".casefold() | 'strasse' |
Searching Methods
| Method | Example | Result |
|---|---|---|
find() | "Hello World".find("World") | 6 |
rfind() | "Hello World".rfind("o") | 7 |
index() | "Hello World".index("World") | 6 |
count() | "banana".count("a") | 3 |
startswith() | "file.txt".startswith("file") | True |
endswith() | "file.txt".endswith(".txt") | True |
find() returns -1 if not found; index() raises ValueError. Use find() when “not found” is a normal case, index() when the substring’s absence signals a bug that should surface loudly.
Validation Methods
The is* family answers yes/no questions about a string’s content — used for quick input validation before parsing or type conversion (see 8.1 Introduction to Type Conversion).
| Method | Example | Result |
|---|---|---|
isalpha() | "abc123".isalpha() | False |
isdigit() | "123".isdigit() | True |
isalnum() | "abc123".isalnum() | True |
islower() / isupper() | "hello".islower() | True |
isspace() | " ".isspace() | True |
isidentifier() | "var_1".isidentifier() | True |
Modification Methods
| Method | Example | Result |
|---|---|---|
replace() | "Hello World".replace("World","Python") | 'Hello Python' |
strip() | " hi ".strip() | 'hi' |
lstrip() / rstrip() | " hi ".lstrip() | 'hi ' |
removeprefix() | "unit_test.py".removeprefix("unit_") | 'test.py' |
removesuffix() | "image.png".removesuffix(".png") | 'image' |
Splitting and Joining Methods
| Method | Example | Result |
|---|---|---|
split() | "a,b,,c".split(",") | ['a','b','','c'] |
rsplit() | "a,b,,c".rsplit(",",1) | ['a,b,','c'] |
splitlines() | "line1\nline2".splitlines() | ['line1','line2'] |
partition() | "k=v=x".partition("=") | ('k','=','v=x') |
join() | ",".join(["a","b","c"]) | 'a,b,c' |
join() does the reverse of split() — it merges a list of strings into one, inserting the given separator between each piece. It’s the efficient way to build a string from parts (see 9.11 Memory and Performance).
Alignment Methods
| Method | Example | Result |
|---|---|---|
center() | "hi".center(6,"*") | '**hi**' |
ljust() | "hi".ljust(6,"*") | 'hi****' |
rjust() | "hi".rjust(6,"*") | '****hi' |
zfill() | "7".zfill(3) | '007' |
Encoding and Translation Methods
encode() converts a Unicode str into raw bytes using a given character encoding, usually UTF-8 — required whenever text needs to leave Python as a byte stream, such as writing to a file or sending over a network (see 5.7 Binary Data Types).
>>> "café".encode("utf-8")
b'caf\xc3\xa9'
maketrans() builds a character-mapping table; translate() applies it in one fast pass — useful for bulk character substitution without chaining many replace() calls.
>>> table = str.maketrans("aeiou", "12345")
>>> "hello world".translate(table)
'h2ll4 w4rld'
Quick Interview Answer
“The
strmethod set breaks down into a handful of purpose-based groups: case conversion (upper/lower/title), searching (find/index/count/startswith), validation (theis*family), modification (replace/strip), splitting/joining (split/join— mirror images of each other), alignment (center/ljust/zfill), and encoding (encode/translate). The one recurring theme is that every single one returns a new string rather than mutating the original, sincestris immutable.”
Common Mistakes
- Using
index()when “not found” is a normal, expected outcome — it raisesValueErrorinstead of returning a sentinel, sofind()is usually the safer default for optional matches. - Calling
strip()expecting it to remove whitespace from the middle of a string — it only trims from the two ends; usereplace(" ", "")or a regex for interior whitespace. - Forgetting
split()with no arguments splits on any run of whitespace and drops empty strings, whilesplit(",")with an explicit separator does not —"a,,b".split(",")keeps the empty string between the commas.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form