Byte by Byte › Book 7: Networks, Programming and Machine Learning › Chapter 4: Working with Strings
Chapter 4: Working with Strings
You will learn: how Python stores text as strings, escape characters, indexing and negative indexing, slicing, why strings are immutable, the most useful string methods, the in operator, looping through strings, ord() and chr(), formatted output, and how to write a Caesar cipher program and a letter-frequency counter.
🔎 The Case
Beautine arrived at Snowpeak with her tail fluffed out to twice its usual size, which meant she was either furious or delighted. It turned out to be both.
"I am Keeper of Records," she announced, "and nobody asked me to keep these records. So I kept them anyway." She had copied every post about the fake picture from every message board in Memunic: 12,384 of them. "They are a mess," she added. "Capitals everywhere. Extra spaces. Spelling that would make Kachui weep."
Memoon read a few on screen.
" The Guardian SHOWS his true face! #Simbah "
"cant believe it... poor rabbits #simbah"
"This is OBVIOUSLY edited, Simbha would never!!!"
"Last year," said Memoon, "I only used Python for numbers and turtles. I never used it for words."
"Words are just data," said Nimo. "Every letter is a number underneath, remember? Python can handle text as easily as numbers, if you know how to hold it."
Memoon opened IDLE and typed the first post into a variable. If she could understand one post completely, she could understand twelve thousand.
💡 The Concepts
Strings. In Python, text is stored as a string: a sequence of characters inside quotation marks. You met strings in Book 6 as the str data type. Single and double quotes both work; triple quotes let a string run over several lines.
name = "Memoon" village = 'Moonbrook' notice = """Truth Desk Open every day Ask before you share"""
A string can hold letters, digits, spaces, punctuation, emoji and characters from any language, because Python 3 uses Unicode (Book 6).
Basic operations.
| Operation | Example | Result |
|---|---|---|
| Length | len("Snowpeak") | 8 |
| Join (concatenate) | "Snow" + "peak" | "Snowpeak" |
| Repeat | "ha" * 3 | "hahaha" |
Compare "cat" == "Cat" False (case matters)
| Convert a number | str(42) | "42" |
Escape characters. Some characters cannot be typed directly inside a string, so Python uses a backslash followed by a letter, called an escape character (or escape sequence).
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\' | A single quote inside a single-quoted string |
\" | A double quote inside a double-quoted string |
\\ | A real backslash |
print("Line one\nLine two\tTabbed")
print('It\'s Memoon')
Output:
Line one Line two Tabbed It's Memoon
Indexing. Each character in a string has a position number called an index. Python counts from 0, not 1. You can also count backwards from the end using negative indexes: −1 is the last character.
| Character | S | N | O | W | P | E | A | K |
|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| Negative index | −8 | −7 | −6 | −5 | −4 | −3 | −2 | −1 |
word = "SNOWPEAK" print(word[0], word[3], word[-1], word[-2])
Output: S W K A . Asking for an index that does not exist, such as word[8] , gives an IndexError .
Slicing. A slice takes a piece of a string: text[start:stop:step] . It starts at start and stops just before stop . Leave out start to begin at the beginning; leave out stop to go to the end; step says how many to jump.
| Slice | Meaning | Result |
|---|---|---|
word[0:4] | Indexes 0, 1, 2, 3 | "SNOW" |
word[4:] | From 4 to the end | "PEAK" |
word[:3] | From the start up to (not including) 3 | "SNO" |
word[::2] | Every second character | "SOPA" |
word[::-1] | The whole string backwards | "KAEPWONS" |
The rule "stop just before" works like range() in Book 6, and it means word[:4] + word[4:] always gives back the whole word.
Strings are immutable. Immutable means "cannot be changed". You cannot change one character of a string in place:
animal = "lion" animal[0] = "L"
This gives TypeError: 'str' object does not support item assignment . Instead, you build a new string and store it in the variable: animal = "L" + animal[1:] . Every string method below returns a new string; the original stays the same.
String methods. A method is a function that belongs to a particular type of data. You call it with a dot after the value: text.upper() .
| Method | What it does | Example | Result |
|---|
.upper() / .lower( All capitals / all small letters "Hop".upper() "HOP"
)
.title() | Capital at the start of each word | "pebble hollow".title() | "Pebble Hollow" |
.capitalize() | Capital at the start only | "hello there".capitalize( ) | "Hello there" |
.strip() | Removes spaces (and new lines) from both ends | " hi ".strip() | "hi" |
.replace(old, new) Replaces every old with ne "a-b- "a+b+c"
w | c".replace("-", "+") |
.find(sub) Index where sub first "Moonbrook".find(" 4
| appears, or −1 if not found | brook") |
.count(sub) | How many times sub appears | "banana".count("a" ) | 3 |
.startswith(s) / .e True if it starts / ends with s "photo.png".endswi True
ndswith(s) | th(".png") |
.isdigit() | True if every character is a digit | "2026".isdigit() | True |
.isalpha() | True if every character is a letter | "Nimo".isalpha() | True |
.isalnum() | True if every character is a letter or digit | "B7".isalnum() | True |
.isupper() / .islow True if all letters are capitals / "OK".isupper() True
er() | small |
.split() | Breaks a string into a list of words | "a b c".split() | ['a', 'b', 'c'] |
You will use .split() and the lists it makes in Chapter 5.
The in operator. in checks whether one string appears inside another, giving True or False :
post = "cant believe it... poor rabbits #simbah"
if "#simbah" in post:
print("Contains the misspelled tag")
not in does the opposite.
Looping through a string. A for loop can visit each character in turn:
for ch in "Nimo":
print(ch)
If you also need each character's position, loop over the indexes: for i in range(len(text)): and use text[i] . Loops like these let you build a new string one character at a time, using the accumulator pattern from Book 6 with a string that starts empty ( "" ).
Characters are numbers: ord() and chr() . In Book 6 you learned that every character has a code number (ASCII and Unicode). ord() gives a character's code; chr() gives the character for a code.
print(ord("A"), ord("a"), chr(77))
Output: 65 97 M . Capital letters A to Z are codes 65 to 90, so ord(letter) - ord("A") turns a capital letter into a number from 0 to 25: exactly what the Caesar formula needs.
Formatted output. f-strings (Book 6) can also line text up and round numbers. Inside the braces, after a colon: < means left-align, > right-align, ^ centre, a number sets the width, and .1f means one decimal place.
print(f"{'Name':<10}|{'Score':>6}")
print(f"{'Memoon':<10}|{95.456:>6.1f}")
Output:
Name | Score Memoon | 95.5
A complete example: cleaning a post.
post = " The Guardian SHOWS his true face! #Simbah "
print(len(post))
clean = post.strip().lower()
print(clean)
print(clean.find("guardian"))
print(clean.count("a"))
print("#simbah" in clean)
print(clean.replace("#simbah", "#simbha"))
Output:
45 the guardian shows his true face! #simbah 4 4 True the guardian shows his true face! #simbha
Notice post.strip().lower() : calling one method on the result of another is called method chaining. It reads left to right: strip first, then make lower case. Cleaning text into one standard form like this before searching it is called normalising the text, and it is the first step in almost every program that works with real-world writing, including the natural language processing you met in Book 6.
Career Spotlight: Data engineer. Real data is messy: extra spaces, mixed capitals, missing values, typing errors. Data engineers write programs that clean and organise data so that analysts and AI systems can use it. Most of their code looks a lot like the cleaning program above.

🛠️ Build It
Save all programs in Documents > Python Practice > Book 7.
Activity 1: String explorer. Type and run this, then predict the output before each line runs:
word = "SNOWPEAK" print(word[0], word[3], word[-1], word[-2]) print(word[0:4], word[4:], word[:3], word[::2], word[::-1])
Now change word to your own name. Print the first letter, the last letter, the first three letters and your name backwards.
Activity 2: Caesar cipher program. Save as caesar.py . This version works with capital letters and leaves everything else (spaces, punctuation) unchanged.
message = input("Message (in CAPITALS): ")
key = int(input("Key (1-25): "))
mode = input("Encrypt or decrypt (e/d)? ").lower()
if mode == "d":
key = -key
result = ""
for ch in message:
if ch.isalpha():
number = ord(ch) - ord("A")
new_number = (number + key) % 26
result = result + chr(new_number + ord("A"))
else:
result = result + ch
print("Result:", result)
Test it: decrypt the echo bird note SKDVH WZR: WKH PLUURU HQJLQH. PHHW DW WKH ROG PLOO. J with key 3. Then improve the program: add message = message.upper() after the first line so it also accepts small letters.
How it works: subtracting the key for decryption is the same as adding a negative key, and % 26 makes the alphabet wrap round in both directions, because Python's % always gives a result from 0 to 25 here, even for negative numbers.
Activity 3: Letter-frequency counter. Save as frequency.py . It draws a bar of # symbols for each letter that appears.
text = input("Paste the ciphertext: ").upper()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in alphabet:
n = text.count(letter)
if n > 0:
print(f"{letter}: {'#' * n} {n}")
Run it on the echo bird note. You should see H: ####### 7 as the longest bar, with W: ##### 5 next.
Activity 4: Palindrome checker. A palindrome reads the same forwards and backwards, ignoring spaces, punctuation and capitals, like malayalam or Was it a car or a cat I saw.
phrase = input("Enter a word or phrase: ")
letters = ""
for ch in phrase.lower():
if ch.isalpha():
letters = letters + ch
if letters == letters[::-1]:
print(f'"{phrase}" is a palindrome.')
else:
print(f'"{phrase}" is not a palindrome.')
Activity 5: Passphrase strength meter. Write a program that asks for a passphrase and gives it a score: 2 points if it has 12 or more characters (or 1 point for 8 to 11), plus 1 point each for containing a digit, a capital letter, and a space or symbol. Print the score out of 5 and a message such as "Weak", "Okay" or "Strong". (Hint: loop through the characters and set True / False variables such as has_digit .) Test it with memoon (0), Skate2026 (3) and purple tiger dances at 7 pm! (4). Never test it with a real password you use.
Unplugged: Human slicer. Eight people stand in a line, each holding a card with one letter of a word. Everyone else calls out slices, like [2:5] or [::-1] or [-3:] , and the people in that slice step forward in order. Who gets it wrong most often: the people who forget to start at 0, or the people who forget that stop is not included?
✅ Case Closed
By midnight Memoon had a program that took any post, cleaned it, and checked it for words that mattered. She ran it on sample after sample from Beautine's records. Most of the posts were ordinary villagers: some angry, some upset, some saying clearly that the picture must be fake.
But one thing kept appearing. The tag #simbah .
"That's a spelling mistake," said Beautine, outraged. "His name has an H at the end, not an A-H."
"Exactly," said Memoon. "Real villagers spell it lots of different ways, or don't use a tag at all. But these posts all make the same mistake, written the same way." She ran .count("#simbah") over a long string of a hundred posts joined together. Thirty-eight of them. "Someone wrote one message with a typo, and a machine copied it again and again."
Vega was reading over her shoulder. "So the misspelling is like a fingerprint."
"A fingerprint," agreed Memoon. "But I've only checked a hundred posts, one string at a time. I need to hold all twelve thousand at once, sort them, count them and pick out every account that used it." She rubbed her eyes. "I need something bigger than a string."
❓ Test Yourself
- What is a string? Write three different ways to create one in Python.
- What is printed? (a)
len("Pearlhaven")(b)"Na" * 4(c)"Pebble" + " " +
"Hollow"
- For
place = "RIVERBEND", what are: (a)place[0](b)place[-1](c)place[2:5](d)place[:5](e)place[5:](f)place[::-1]? - What does it mean that strings are immutable? How do you "change" a string?
- Which method would you use to: (a) remove spaces at both ends, (b) count how many times "the" appears, (c) check if a text contains only digits, (d) find the position of "@" in an email address?
- What does
"Moonbrook".find("x")return, and why? - What is the output of
print("Hello\nWorld")? - What do
ord("C")andchr(68)give? - Encrypt
PYTHONwith a Caesar key of 5. Show the number for each letter. - Fill in the blank: calling one method on the result of another, like
text.strip().lower(), is called method ________. - Challenge: Write a program that asks for a sentence and prints how many vowels it contains, how many words it has (hint: count the spaces, or use
.split()andlen()), and the sentence with every vowel replaced by*.
📚 Key Terms
- String: a sequence of characters, written inside quotation marks.
- Concatenation: joining strings together with
+. - Escape character: a backslash code such as
\nfor a special character inside a string. - Index: the position number of a character, counting from 0.
- Negative index: a position counted from the end, where −1 is the last character.
- Slice: part of a string, written
[start:stop:step]; stops just beforestop. - Immutable: cannot be changed after it is created.
- Method: a function that belongs to a type of data, called with a dot.
- Method chaining: calling one method on the result of another.
- Normalising: cleaning data into one standard form, such as lower case with no extra spaces.
ord()/chr(): functions that give a character's code number / the character for a code.- Palindrome: a word or phrase that reads the same forwards and backwards.
Keep learning with Byte by Byte
Explore Book 7: Networks, Programming and Machine Learning. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment