Who this is for:
- Grade 8–9 students who already know Python basics (variables, input, loops, functions)
Why this matters:
Strings are everywhere: names, chat messages, file paths, and more. Learning to slice, clean, search, and format strings makes your programs easier to read and more powerful.
Goals:
- Treat strings as sequences (indexing and slicing)
- Clean and transform text with common string methods
- Search inside strings and replace parts safely
- Split and join words
- Format strings neatly with f-strings
- Build a small text tool using these skills
Key ideas and examples
1) Strings are sequences
- You can think of a string as a row of characters, each with a position (index).
- Indexing starts at 0. Negative indexes count from the end.
Example:
text = "Python"
print(text[0]) # 'P'
print(text[-1]) # 'n'
print(text[1:4]) # 'yth' (from index 1 up to, but not including, 4)
print(text[:2]) # 'Py'
print(text[2:]) # 'thon'
print(text[::-1]) # 'nohtyP' (reversed)2) Strings are immutable
- You can't change a string in place. You create new strings instead.
Example:
name = "Sam"
# name[0] = "J" # This would cause an error
name = "J" + name[1:]
print(name) # 'Jam'3) Concatenation and repetition
- Use + to join strings and * to repeat.
Example:
greet = "Hi" + " " + "there"
echo = "ha" * 3
print(greet) # 'Hi there'
print(echo) # 'hahaha'4) Escaping and multi-line strings
- Use backslash to escape quotes or special characters. Triple quotes for multi-line.
Example:
quote = "She said, \"Hello!\""
path = "C:\\Users\\You"
haiku = """Code flows softly
over keys and tiny bugs
fixed at break of day"""
print(quote)
print(path)
print(haiku)5) Change case and trim whitespace
- .lower(), .upper(), .title()
- .strip() removes spaces at both ends (or chosen characters), .lstrip(), .rstrip()
Example:
raw = " hello PyVerse! "
clean = raw.strip()
print(clean) # 'hello PyVerse!'
print(clean.upper()) # 'HELLO PYVERSE!'
print("mr. bean".title()) # 'Mr. Bean'6) Find, count, and replace
- 'in' checks membership
- .find(x) returns the index or -1
- .count(x) counts occurrences
- .replace(old, new[, count]) returns a new string
Example:
txt = "banana bread bandana"
print("bread" in txt) # True
print(txt.find("band")) # 13
print(txt.count("ana")) # 4
print(txt.replace("ana", "ANA", 2)) # first 2 replacements7) Starts/ends with
- Use these to quickly check prefixes/suffixes.
Example:
filename = "report_2025.csv"
print(filename.startswith("report_")) # True
print(filename.endswith(".csv")) # True8) Split and join
- .split() turns a string into a list of words.
- .join(list) glues a list of strings back into one string.
- split with no argument handles multiple spaces neatly.
Example:
line = " one two three "
words = line.split() # ['one', 'two', 'three']
print(words)
joined = "-".join(words)
print(joined) # 'one-two-three'9) Check what characters are inside
- .isalpha(), .isdigit(), .isalnum(), .isspace()
Example:
code = "X9Y"
print(code.isalnum()) # True
print("123".isdigit()) # True
print("Hi".isalpha()) # True
print(" \t".isspace())# True10) Neat formatting with f-strings
- f-strings insert variables directly and support simple formatting.
Example:
name = "Leena"
score = 9.456
print(f"Hi {name}, your score is {score:.1f}/10") # rounds to 1 decimalCommon mini-patterns
A) Normalize spaces
text = " this has extra spaces "
normalized = " ".join(text.split())
print(normalized) # 'this has extra spaces'B) Safe substring search
msg = "no spoilers please"
idx = msg.find("spoilers")
if idx != -1:
print(f"Found at index {idx}")
else:
print("Not found")C) Quick palindrome check (ignoring spaces and case)
s = "Never odd or even"
simple = s.replace(" ", "").lower()
print(simple == simple[::-1]) # TrueMini Project: Acronym and Hashtag Maker
Goal:
Build a small tool that:
- Cleans the input phrase
- Creates an acronym (first letter of each word, uppercase)
- Builds a hashtag version of the phrase (#TitleCaseWithNoSpaces)
Step-by-step:
- Ask the user for a phrase.
- Strip leading/trailing spaces and normalize multiple spaces to single spaces.
- Create an acronym by taking the first character of each word and making it uppercase.
- Create a hashtag that starts with # and uses Title Case with no spaces.
Starter code (fill in the blanks if you want a challenge):
phrase = input("Enter a phrase: ")
# 1) Clean: strip and normalize spaces
clean = " ".join(phrase.strip().split())
# 2) Acronym: first letters of each word, uppercased
words = clean.split()
acronym = "".join(w[0] for w in words).upper()
# 3) Hashtag: Title Case + no spaces
hashtag = "#" + "".join(w.title() for w in words)
print(f"Cleaned: {clean}")
print(f"Acronym: {acronym}")
print(f"Hashtag: {hashtag}")Sample run:
Enter a phrase: national aeronautics and space administration
Cleaned: national aeronautics and space administration
Acronym: NASA
Hashtag: #NationalAeronauticsAndSpaceAdministrationChallenge ideas (optional):
- If phrase is empty after cleaning, ask again.
- Limit hashtag length to 30 characters and add "..." if it's longer.
- Censor a banned word list by replacing matches with "***" using .replace().
Tips and pitfalls
- Strings are immutable: methods like replace, strip, lower return a new string. Assign the result to keep the changes.
- .find returns -1 if not found; don't slice using -1 unless you mean the last character.
- split() with no arguments is great for messy spacing.
- When joining, make sure you have a list of strings (not numbers). Convert with str() if needed.
Summary
- Strings are sequences you can index and slice.
- Use methods like strip, lower, replace, find, count, split, and join to transform text.
- f-strings make your output clean and readable.
- With a few techniques, you can build practical text tools like an acronym and hashtag maker.