🌱
Basic
Methods · Slicing · format() · f-strings · encode
Week 8 — String Methods & Formatting
Strings are immutable sequences with a rich method library. Learn to slice, search, replace, split, join, and format text for real-world use.
stringf-stringformatsplitjoinregex
Duration
⏱ 2 hours
Level
📊 Beginner
Prerequisite
🎯 Week 6
OUTCOME
Write a text cleaning and analysis utility
What you'll learn
- 1Use upper, lower, strip, replace, split, join
- 2Format strings with f-strings and format()
- 3Slice strings like lists
- 4Check membership with in and startswith/endswith
- 5Understand string immutability
1. String Basics
python
s = " Hello, World! "
print(s.upper()) # " HELLO, WORLD! "
print(s.lower()) # " hello, world! "
print(s.strip()) # "Hello, World!"
print(s.strip().replace("World", "Python"))
print(len(s)) # 18ℹ️
Strings are immutable — every method returns a new string; the original is unchanged.
2. Split & Join
python
csv = "Alice,Bob,Charlie,Diana"
names = csv.split(",") # list of strings
print(names) # ['Alice', 'Bob', ...]
joined = " | ".join(names)
print(joined) # Alice | Bob | Charlie | Diana3. String Formatting
python
name, score = "Alice", 92.5
# f-string (recommended)
print(f"{name} scored {score:.1f}")
# format()
print("{} scored {:.1f}".format(name, score))
# Width & alignment
print(f"{name:<10}|{score:>8.2f}") # left|right aligned4. Useful Methods
| Method | Example | Result |
|---|---|---|
| find(sub) | "hello".find("ll") | 2 |
| count(sub) | "banana".count("a") | 3 |
| startswith(s) | "hello".startswith("he") | True |
| endswith(s) | "hello".endswith("lo") | True |
| isdigit() | "123".isdigit() | True |
| isalpha() | "abc".isalpha() | True |
| zfill(n) | "42".zfill(5) | "00042" |
5. Common Mistakes
- Forgetting that strings are immutable: s.upper() doesn't change s — you must reassign: s = s.upper().
- split() with no argument splits on any whitespace and removes empty strings; split(' ') preserves them.
- "hello"[0] = 'H' → TypeError. Create a new string: 'H' + "hello"[1:].
💻 Examples
Run these examples and check the output yourself.
01_string_methods.py— Chaining common string methods
CODE
raw = " python is AWESOME! "
cleaned = raw.strip().lower()
print(cleaned)
print(cleaned.count("is"))
print(cleaned.replace("python", "coding"))
▶ Output
python is awesome!
1
coding is awesome!02_csv_parser.py— Parse CSV line into named fields
CODE
line = "Alice,25,Seoul,Developer"
fields = line.split(",")
labels = ["Name", "Age", "City", "Job"]
for label, value in zip(labels, fields):
print(f"{label:6}: {value}")
▶ Output
Name : Alice
Age : 25
City : Seoul
Job : Developer03_format.py— Table formatting with f-strings
CODE
students = [("Alice", 95), ("Bob", 82), ("Charlie", 71)]
print(f"{'Name':<10} {'Score':>6}")
print("-" * 18)
for name, score in students:
print(f"{name:<10} {score:>6}")
▶ Output
Name Score
------------------
Alice 95
Bob 82
Charlie 71📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
Password Validator
Goal: Check if a password meets complexity requirements.
Requirements
- Minimum 8 characters
- At least one digit (any char.isdigit())
- At least one uppercase letter
- Print each failed rule
Sample I/O
Password: hello
Failed: too short
Failed: no digit
Failed: no uppercase▶Toggle solution
SOLUTION
pw = input("Password: ")
if len(pw) < 8:
print("Failed: too short")
if not any(c.isdigit() for c in pw):
print("Failed: no digit")
if not any(c.isupper() for c in pw):
print("Failed: no uppercase")
if len(pw) >= 8 and any(c.isdigit() for c in pw) and any(c.isupper() for c in pw):
print("Password OK")
Exercise 2
Word Reverser
Goal: Reverse each word in a sentence while keeping word order.
Requirements
- Read a sentence from input
- Reverse each word individually
- Join with spaces and print
Sample I/O
Input: Hello World Python
Output: olleH dlroW nohtyP▶Toggle solution
SOLUTION
sentence = input('Input: ')
result = ' '.join(w[::-1] for w in sentence.split())
print('Output:', result)
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗