Python - String Methods
Overview
Estimated time: 25–40 minutes
This page is a practical reference of common string methods with concise examples, expected output, and notes on behavior and pitfalls.
Learning Objectives
- Recall and apply core string methods (split, join, replace, find, startswith, endswith, strip, case conversions, etc.).
- Understand when to choose methods vs slicing or regex.
- Avoid common Unicode and whitespace pitfalls.
Examples
s = " Hello, World! "
print(s.strip()) # remove outer whitespace
print(s.lower()) # lowercase
print("hi,there".split(","))
print(", ".join(["a","b","c"]))
print("banana".replace("na","NA"))
Expected Output:
Hello, World!
hello, world!
['hi', 'there']
a, b, c
baNANA
Guidance & Patterns
- Show
partition
/rpartition
vssplit
when you need exactly 3 parts. - Explain
find
/rfind
(return -1) vsindex
/rindex
(raise ValueError). - Demonstrate
startswith
/endswith
with tuples for multiple prefixes/suffixes.
Best Practices
- Unicode: normalization (NFC/NFD) can affect comparisons; consider
unicodedata.normalize
for canonical forms. - Performance: prefer chaining simple methods over regex for trivial cases; measure with
timeit
.
Method Walkthrough
split(sep=None, maxsplit=-1)
,rsplit
join(iterable)
strip
,lstrip
,rstrip
replace(old, new, count=-1)
find
/rfind
,index
/rindex
startswith
/endswith
count
capitalize
,title
,upper
,lower
,casefold
removeprefix
,removesuffix
(3.9+)
Checks for Understanding
- How do you split only on the first dash in
"a-b-c"
? - What’s the difference between
find
andindex
?
Show answers
"a-b-c".split("-", 1)
orpartition("-")
find
returns -1 when not found;index
raises ValueError.