Chapter 9 of 12
Python's string methods are extensive and elegant. Strings are immutable, so all methods return new strings rather than modifying the original.
text = " Hello, World! "
# Case
text.upper() # " HELLO, WORLD! "
text.lower() # " hello, world! "
text.title() # " Hello, World! "
text.capitalize() # " hello, world! " (only first char)
# Whitespace
text.strip() # "Hello, World!" (both ends)
text.lstrip() # "Hello, World! " (left only)
text.rstrip() # " Hello, World!" (right only)
# Searching
text.find("World") # 9 (index of first match, -1 if not found)
text.count("l") # 3
text.startswith(" H") # True
text.endswith("! ") # True
"World" in text # True
# Modifying (returns new string)
text.replace("World", "Python") # " Hello, Python! "
text.replace(" ", "", 1) # replaces only first occurrence
# Splitting and joining
"a,b,c".split(",") # ["a", "b", "c"]
"Hello World".split() # ["Hello", "World"] (splits on whitespace)
", ".join(["a", "b", "c"]) # "a, b, c"
# Padding
"42".zfill(5) # "00042"
"left".ljust(10) # "left "
"right".rjust(10) # " right"name = "Nelson"
score = 98.754
courses = 12
# Basic embedding
f"Hello, {name}!" # "Hello, Nelson!"
# Expressions inside {}
f"2 + 2 = {2 + 2}" # "2 + 2 = 4"
f"Upper: {name.upper()}" # "Upper: NELSON"
# Formatting numbers
f"Score: {score:.2f}" # "Score: 98.75"
f"Score: {score:.0f}%" # "Score: 99%"
f"Courses: {courses:,}" # "Courses: 12"
f"Pi: {3.14159:.3f}" # "Pi: 3.142"
f"Hex: {255:#x}" # "Hex: 0xff"
# Alignment
f"{'left':<10}|{'right':>10}" # "left | right"
# Debug (Python 3.8+)
f"{score=}" # "score=98.754" โ print name and value together