Day 8: String Manipulation & Formatting
1. Learning Objectives
By the end of Day 8, you will be able to:
Master Python's most useful string methods (
upper(),lower(),strip(),split(),join(),replace(), and more)Slice and dice strings with ease
Format output professionally using f-strings,
.format(), and%formattingUse escape sequences for special characters
Clean and process text input from users
Write more readable, maintainable code by formatting strings correctly
2. Concept Explanation
2.1 Strings as Immutable Sequences
Remember from Day 1: strings are immutable – you cannot change a character in place, but you can create a new string based on the old one.
text = "hello"
# text[0] = "H" # ❌ TypeError
text = "H" + text[1:] # ✅ Creates a new string "Hello"
Because strings are sequences, you can use indexing and slicing on them exactly like lists:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[0:3]) # Pyt
print(word[::-1]) # nohtyP (reversed)
2.2 Essential String Methods
Strings come packed with built-in methods. Here are the ones you'll use every day:
| Method | What it does | Example | Result |
|---|---|---|---|
.upper() |
Convert to uppercase | "hello".upper() |
"HELLO" |
.lower() |
Convert to lowercase | "HELLO".lower() |
"hello" |
.title() |
Capitalize each word | "john smith".title() |
"John Smith" |
.capitalize() |
Capitalize first letter | "hello WORLD".capitalize() |
"Hello world" |
.strip() |
Remove leading/trailing whitespace | " hi ".strip() |
"hi" |
.lstrip() / .rstrip() |
Remove whitespace from left/right | " hi".lstrip() |
"hi" |
.split() |
Split into list of words | "a,b,c".split(",") |
['a', 'b', 'c'] |
.join() |
Join list into string | "-".join(['a','b']) |
"a-b" |
.replace(old, new) |
Replace substrings | "Hello Bob".replace("Bob","Alice") |
"Hello Alice" |
.find(sub) |
Find index of substring (-1 if not found) | "abc".find("b") |
1 |
.count(sub) |
Count occurrences | "abba".count("a") |
2 |
.startswith(prefix) |
Check prefix | "report.pdf".startswith("report") |
True |
.endswith(suffix) |
Check suffix | "report.pdf".endswith(".pdf") |
True |
.isdigit() |
Check if all characters are digits | "123".isdigit() |
True |
.isalpha() |
Check if all characters are letters | "abc".isalpha() |
True |
Important: Most methods return a new string; they don't change the original.
text = " Python Basics "
cleaned = text.strip() # cleaned is a new string
print(text) # " Python Basics " (original unchanged)
2.3 String Slicing in Depth
Slicing syntax: string[start:stop:step]
start: index to begin (inclusive), defaults to 0.
stop: index to end (exclusive), defaults to length of string.
step: how many characters to skip, defaults to 1.
s = "0123456789"
print(s[2:7]) # "23456" (2 to 6)
print(s[:5]) # "01234" (first 5)
print(s[5:]) # "56789" (from 5 to end)
print(s[::2]) # "02468" (every second)
print(s[::-1]) # "9876543210" (reverse)
2.4 Escape Sequences
Special characters inside strings:
| Sequence | Meaning |
|---|---|
\n |
Newline |
\t |
Tab |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
\u |
Unicode (e.g., \u2764 → ❤) |
print("Line1\nLine2") # prints on two lines
print("C:\\Users\\Public") # C:\Users\Public
print("He said, \"Hi!\"") # He said, "Hi!"
Raw strings ignore escape sequences. Prepend r:
print(r"C:\new\folder") # prints C:\new\folder (no newline escape)
2.5 String Formatting — Three Ways
2.5.1 f-strings (Python 3.6+, recommended)
name = "Alice"
age = 28
print(f"{name} is {age} years old.")
You can embed any expression inside {}:
print(f"5 + 3 = {5 + 3}")
print(f"Age next year: {age + 1}")
Formatting numbers with f-strings:
pi = 3.14159265
print(f"Pi to 2 decimals: {pi:.2f}") # 3.14
print(f"Pi in scientific: {pi:.2e}") # 3.14e+00
price = 49.99
print(f"Price: ${price:.2f}") # $49.99
percent = 0.853
print(f"Percent: {percent:.1%}") # 85.3%
large = 1234567
print(f"Large: {large:,}") # 1,234,567
Alignment:
print(f"{'Name':<10} {'Age':>5}") # Name left-aligned in 10 chars, Age right-aligned in 5
print(f"{name:<10} {age:>5}")
2.5.2 .format() method (older, but still used)
print("{} is {} years old.".format(name, age))
print("{1} is {0} years old.".format(age, name)) # positional
print("{n} is {a} years old.".format(n="Bob", a=30)) # keyword
2.5.3 % operator (C‑style, legacy)
print("%s is %d years old." % (name, age))
print("Pi: %.2f" % pi)
Recommendation: Use f-strings for all new code – they're fastest, most readable, and most powerful.
2.6 Combining Strings (Concatenation & Repetition)
greeting = "Hello, " + name + "!" # + concatenates
chant = "Python! " * 3 # * repeats
print(chant) # "Python! Python! Python! "
Watch out for type errors:
age = 28
print("Age: " + age) # ❌ TypeError: can't add str to int
print("Age: " + str(age)) # ✅
2.7 Cleaning and Validating User Input
A common real-world pattern:
user_input = input("Enter your email: ").strip().lower()
if "@" in user_input and "." in user_input:
print("Looks like an email.")
else:
print("Invalid email format.")
3. Code Examples
Example 1: Password Validator
def is_strong_password(pw):
"""Check if password has at least 8 chars, one digit, one uppercase."""
return (len(pw) >= 8 and
any(c.isdigit() for c in pw) and
any(c.isupper() for c in pw))
pw = input("Create password: ")
if is_strong_password(pw):
print("Strong password!")
else:
print("Weak password. Needs 8+ chars, a digit, and an uppercase letter.")
Example 2: CSV Parser
data = "apple,banana,cherry,date"
fruits = data.split(",")
print(fruits) # ['apple', 'banana', 'cherry', 'date']
combined = " & ".join(fruits)
print(combined) # "apple & banana & cherry & date"
Example 3: Table Formatter
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
print(f"{'Name':<10} {'Score':>6}")
print("-"*17)
for name, score in students:
print(f"{name:<10} {score:>5}")
Output:
Name Score
-----------------
Alice 85
Bob 92
Charlie 78
4. Hands-On Exercises
Exercise 1: Name Formatter
Ask for a user's full name (e.g., " john doe "). Strip it, then print it in title case and uppercase. Also print the initials (first letter of first and last name).
Exercise 2: Word Reverser
Ask for a sentence, split it into words, reverse the order of words, and join them back with spaces. Print the result.
Exercise 3: Email Extractor
Given a string like "Contact us at support@company.com or sales@company.org", extract all email addresses. (Hint: split by spaces, check for "@".)
Exercise 4: Receipt Generator
Ask for item name, quantity, and unit price. Print a receipt using f-strings:
=== RECEIPT ===
Item: Apples
Qty: 5
Unit Price: $1.25
Total: $6.25
================
Format the total to exactly 2 decimal places.
Exercise 5: Palindrome Checker
Ask for a word (ignore case and punctuation). Check if it's a palindrome (reads the same forwards and backwards) using slicing.
5. Applied Challenge Task 🏗️
Text Analyzer Tool
Build a program that reads a block of text (provided by the user) and provides statistics:
Total number of characters (including spaces)
Total number of words
Total number of unique words (case-insensitive)
The most frequent word and how many times it appears
The text in title case and in reverse (character by character)
A formatted report:
=== TEXT ANALYSIS ===
Characters: 450
Words: 78
Unique words: 56
Most frequent: 'python' (5 times)
=====================
Optional extensions:
Remove punctuation before counting words (use
.replace()with punctuation characters orstr.maketrans)Show the top 3 most frequent words
Format the output as a table
6. Brief Review Summary
| Concept | Key Points |
|---|---|
| String methods | .upper(), .lower(), .strip(), .split(), .join(), .replace(), .find(), .startswith(), .endswith() |
| Slicing | s[start:stop:step] – works like list slicing |
| Escape sequences | \n, \t, \\, \", \uXXXX |
| Raw strings | r"..." – ignore escapes |
| f-strings | f"text {variable:format}" – best formatting tool |
| Format specifiers | :.2f, :.1%, :,, <, > for alignment |
| Concatenation | + joins strings; * repeats them |
| Type casting | Always convert numbers to str() before concatenation |
| Input cleaning | Chain .strip().lower() for consistent parsing |
7. Preview of Next Topic — Day 9
Tomorrow we'll learn to make your programs persistent:
File Handling — reading from and writing to files
Built-in
open()function and modes (r,w,a,r+)Reading line by line, reading entire files
Writing data to files
Using
withstatement (beginning of context managers)
🎯 Your Action Items for Day 8:
✅ Complete all 5 exercises
✅ Build the Text Analyzer Tool
✅ Experiment with f-string formatting — try to produce a neatly aligned table
Comments
Post a Comment
Leave us your comments here...