The String Methods You Actually Use

Python has 40+ string methods. Here are the ones that matter, organised by purpose.

Case Conversion

s = "Hello World"
s.upper()       # "HELLO WORLD"
s.lower()       # "hello world"
s.title()       # "Hello World"
s.capitalize()  # "Hello world"
s.swapcase()    # "hELLO wORLD"

Checking Content

"abc".isalpha()      # True (letters only)
"123".isdigit()      # True (digits only)
"abc123".isalnum()   # True (alphanumeric)
"   ".isspace()      # True (whitespace)
"Hello".isupper()    # False
"HELLO".isupper()    # True
"hello".islower()    # True
"HKDSE".startswith("HK")  # True
"HKDSE".endswith("SE")    # True

Searching

s = "Hello World"
s.find("World")       # 6 (index)
s.find("Xyz")         # -1 (not found)
s.index("World")      # 6 (raises ValueError if not found)
s.count("l")          # 3
"World" in s          # True

Replacing and Modifying

s = "Hello World"
s.replace("World", "HK")      # "Hello HK"
s.replace("l", "L", 2)        # "HeLLo World" (first 2)
s.strip()                     # remove leading/trailing whitespace
s.lstrip()                    # remove leading
s.rstrip()                    # remove trailing
"  hello  ".strip()           # "hello"
"---hi---".strip("-")         # "hi"

Splitting and Joining

# Split by separator
"a,b,c".split(",")            # ["a", "b", "c"]
"hello world".split()         # ["hello", "world"] (whitespace)
"a,b,c,d".split(",", 2)       # ["a", "b", "c,d"] (max 2 splits)

# Join list back to string
",".join(["a", "b", "c"])     # "a,b,c"
" ".join(["HK", "DSE"])       # "HK DSE"

# Split by lines
"line1\nline2".splitlines()  # ["line1", "line2"]

Padding and Alignment

"5".zfill(3)                  # "005" (zero-pad)
"hi".ljust(10, "-")           # "hi--------"
"hi".rjust(10, "-")           # "--------hi"
"hi".center(10, "-")          # "----hi----"

f-string Formatting (Modern)

name = "Chan"
age = 17
f"{name} is {age}"                 # "Chan is 17"
f"{age:03d}"                       # "017" (zero-pad int)
f"{3.14159:.2f}"                   # "3.14"
f"{name:<10}|"                     # "Chan      |"
f"{name:>10}|"                     # "      Chan|"
f"{name:^10}|"                     # "   Chan   |"

Slicing (Very Important)

s = "HKDSE"
s[0]          # "H"
s[-1]         # "E"
s[1:3]        # "KD"
s[:2]         # "HK"
s[2:]         # "DSE"
s[::-1]       # "ESDKH" (reversed)
s[::2]        # "HDE" (every 2nd char)

HKDSE-Relevant Patterns

# Clean user input
name = input("Name: ").strip().title()

# Parse CSV line
fields = "Chan,17,5A".split(",")
name, age_str, cls = fields
age = int(age_str)

# Check if palindrome
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

Drill String Methods in PyForm

Copy this cheat sheet into PyForm and try each method. Active practice beats passive reading.

Open PyForm →