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 vs split when you need exactly 3 parts.
  • Explain find/rfind (return -1) vs index/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

  1. How do you split only on the first dash in "a-b-c"?
  2. What’s the difference between find and index?
Show answers
  1. "a-b-c".split("-", 1) or partition("-")
  2. find returns -1 when not found; index raises ValueError.