🧵 String Patterns: The Art of Playing with Words
Imagine you have a box of letter beads. Each bead has one letter on it. When you string them together, you make words! That’s exactly what a string is in programming—a chain of letters, numbers, or symbols all connected together.
🎯 What You’ll Learn
We’re going on an adventure through the magical land of String Patterns! Here’s our treasure map:
- Strings Fundamentals — What strings are and how they work
- String Manipulation — Changing and playing with strings
- String Compression — Making strings shorter
- Anagram Detection — Finding scrambled word twins
- Palindrome Detection — Words that read the same backwards
- Longest Palindromic Substring — Finding hidden mirror-words
🏠 1. Strings Fundamentals
What is a String?
Think of a string like a necklace of letters. Each letter sits in its own spot, and you can count which spot it’s in!
word = "HELLO"
# 01234 ← Each letter has an "index" number
The first letter is at position 0 (not 1!). That’s just how computers count.
Accessing Letters
Want to grab just one letter? Use square brackets!
word = "HELLO"
print(word[0]) # H (first letter)
print(word[4]) # O (last letter)
print(word[-1]) # O (last, using negative)
🧠 Memory Trick: Negative numbers count backwards from the end. -1 is always the last letter!
Getting String Length
How long is your word? Ask len()!
word = "HELLO"
print(len(word)) # 5
Strings are Immutable
Here’s a big word: immutable. It means you cannot change a string directly.
word = "HELLO"
# word[0] = "J" ❌ This would cause an error!
word = "JELLO" # ✅ Make a new string instead
✂️ 2. String Manipulation
Now let’s learn to change and reshape strings—like playing with clay!
Slicing: Cutting Pieces
You can cut out parts of a string using slicing:
word = "WONDERFUL"
print(word[0:3]) # WON (from 0 to 2)
print(word[3:6]) # DER (from 3 to 5)
print(word[:4]) # WOND (from start to 3)
print(word[4:]) # ERFUL (from 4 to end)
🎯 Pattern: word[start:end] gives letters from start up to (but not including) end.
Reversing a String
Want to flip a word backwards? Use this magic spell:
word = "HELLO"
backwards = word[::-1]
print(backwards) # OLLEH
The [::-1] means “go from start to end, stepping backwards.”
Changing Case
word = "Hello World"
print(word.upper()) # HELLO WORLD
print(word.lower()) # hello world
print(word.title()) # Hello World
Splitting and Joining
Split breaks a string into pieces:
sentence = "I love coding"
words = sentence.split(" ")
print(words) # ['I', 'love', 'coding']
Join glues pieces together:
words = ['I', 'love', 'coding']
sentence = "-".join(words)
print(sentence) # I-love-coding
Common String Methods
text = " hello world "
print(text.strip()) # "hello world"
print(text.replace("l", "L"))
# " heLLo worLd "
print("hello".count("l")) # 2
print("hello".find("e")) # 1
📦 3. String Compression
The Idea
Imagine you have: “AAABBBCC”
Instead of writing all those repeated letters, you could write: “A3B3C2”
This is Run-Length Encoding (RLE)—a way to squish strings!
How It Works
graph TD A["Input: AAABBBCC"] --> B["Count repeats"] B --> C["A appears 3 times"] B --> D["B appears 3 times"] B --> E["C appears 2 times"] C --> F["Output: A3B3C2"] D --> F E --> F
Python Code
def compress(s):
if not s:
return ""
result = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
count += 1
else:
result.append(s[i-1] + str(count))
count = 1
# Don't forget the last group!
result.append(s[-1] + str(count))
return "".join(result)
print(compress("AAABBBCC")) # A3B3C2
When is Compression Useful?
Only when it makes the string shorter!
compress("ABCD") # A1B1C1D1 ← Longer!
Smart tip: Return the original if compressed version is longer.
🔀 4. Anagram Detection
What’s an Anagram?
An anagram is when two words use the exact same letters, just scrambled differently.
| Word 1 | Word 2 | Anagram? |
|---|---|---|
| LISTEN | SILENT | ✅ Yes! |
| HELLO | WORLD | ❌ No |
| EVIL | VILE | ✅ Yes! |
The Sorting Method
The easiest way to check: sort both words and compare!
def are_anagrams(word1, word2):
# Remove spaces, make lowercase
w1 = word1.replace(" ", "").lower()
w2 = word2.replace(" ", "").lower()
# Sort and compare
return sorted(w1) == sorted(w2)
print(are_anagrams("listen", "silent"))
# True
The Counting Method (Faster!)
Count how many of each letter appears:
from collections import Counter
def are_anagrams(word1, word2):
w1 = word1.replace(" ", "").lower()
w2 = word2.replace(" ", "").lower()
return Counter(w1) == Counter(w2)
Why is counting faster?
- Sorting takes O(n log n) time
- Counting takes O(n) time
🪞 5. Palindrome Detection
What’s a Palindrome?
A palindrome reads the same forwards and backwards!
| Word | Backwards | Palindrome? |
|---|---|---|
| RACECAR | RACECAR | ✅ Yes! |
| HELLO | OLLEH | ❌ No |
| MADAM | MADAM | ✅ Yes! |
| A MAN A PLAN A CANAL PANAMA | (same) | ✅ Yes! |
Simple Check
def is_palindrome(s):
# Clean: lowercase, letters only
clean = "".join(c.lower() for c in s
if c.isalnum())
return clean == clean[::-1]
print(is_palindrome("Racecar")) # True
print(is_palindrome("A man a plan a canal Panama"))
# True
Two-Pointer Method
A clever way using two fingers:
def is_palindrome(s):
clean = "".join(c.lower() for c in s
if c.isalnum())
left = 0
right = len(clean) - 1
while left < right:
if clean[left] != clean[right]:
return False
left += 1
right -= 1
return True
graph TD A["RACECAR"] --> B["Compare R and R ✓"] B --> C["Compare A and A ✓"] C --> D["Compare C and C ✓"] D --> E["Middle reached!"] E --> F["It's a palindrome! ✅"]
🌟 6. Longest Palindromic Substring
The Challenge
Given a string, find the longest palindrome hiding inside it!
| String | Longest Palindrome |
|---|---|
| “babad” | “bab” or “aba” |
| “cbbd” | “bb” |
| “racecarxyz” | “racecar” |
Expand Around Center
The trick: every palindrome has a center. We check each position as a possible center and expand outward!
graph TD A["String: abacaba"] --> B["Try each center"] B --> C["Center at 'a': a"] B --> D["Center at 'b': aba"] B --> E["Center at 'a': bacab"] B --> F["Center at 'c': abacaba ⭐"] F --> G["Longest: abacaba"]
Python Code
def longest_palindrome(s):
if not s:
return ""
def expand(left, right):
while left >= 0 and right < len(s):
if s[left] != s[right]:
break
left -= 1
right += 1
return s[left+1:right]
longest = ""
for i in range(len(s)):
# Odd length (single center)
p1 = expand(i, i)
# Even length (double center)
p2 = expand(i, i+1)
# Keep the longest
if len(p1) > len(longest):
longest = p1
if len(p2) > len(longest):
longest = p2
return longest
print(longest_palindrome("babad")) # "bab"
print(longest_palindrome("cbbd")) # "bb"
Why Two Expands?
Palindromes can be:
- Odd length:
aba(center is ‘b’) - Even length:
abba(center is between ‘b’ and ‘b’)
We check both cases!
🎉 Summary: Your String Superpowers
| Power | What It Does | Example |
|---|---|---|
| Fundamentals | Access letters by index | "hello"[0] → "h" |
| Manipulation | Slice, reverse, change | "hello"[::-1] → "olleh" |
| Compression | Shrink repeated letters | "AAABB" → "A3B2" |
| Anagram | Find scrambled twins | "listen" ↔ "silent" |
| Palindrome | Same forwards & backwards | "racecar" ✓ |
| Longest Palindrome | Find hidden mirror-words | "babad" → "bab" |
🚀 You Did It!
You’ve learned to see strings not just as words, but as playgrounds for patterns! Every word is now a puzzle waiting to be solved.
Remember:
- Strings are like necklaces of letters
- You can slice, dice, and rearrange them
- Compression squishes repeated letters
- Anagrams are scrambled twins
- Palindromes are mirror words
- Every string might have a secret palindrome hiding inside!
Keep practicing, and soon you’ll be a String Pattern Master! 🧵✨