B2.1.2 Working with substrings
SL + HLCommand term: Construct1. How ShelfWise makes a book code
A librarian types a messy title. Step through how Python turns " animal farm " into the shelf code ANI-F. Every step makes a new string: the original is never changed.
2. Slice lab: s[start:stop:step]
Blue numbers are positive indexes (from 0), pink numbers are negative indexes (from the end). Leave a box empty to use the default. Then press Animate to watch Python collect each character.
s[::]
or one index s[]3. String methods workbench
Pick a method, change the string or the arguments, and see the result and its type. Notice that s itself never changes: methods return a new value.
s is still 4. ISBN-13 checker: substrings at work
ShelfWise must reject mistyped ISBNs. Step through the checks. Each one uses a substring operation.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Predict the output
What does each line print? Streaks of 3+ score double.
7. 45-second speed round: is the slice right?
True or false? Watch out for the stop index: it is not included.
Expected output
Check my code
shelfwise_v1.py.Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Initials
Write initials(name) that returns the initials of a full name in capitals, each followed by a full stop. Extra spaces must not cause problems.
Starter file (write your code where it says pass # your code here):
def initials(name):
pass # your code here
# ---- tests ----
print(initials("ada lovelace"))
print(initials(" alan mathison turing "))
print(initials("Grace"))
Expected output when your code is correct:
A.L. A.M.T. G.
Hint
name.split() splits on any amount of whitespace.Model solution
def initials(name):
return "".join(word[0].upper() + "." for word in name.split())
# ---- tests ----
print(initials("ada lovelace"))
print(initials(" alan mathison turing "))
print(initials("Grace"))
Task 2: Mask an email address
To protect privacy, ShelfWise shows email addresses like s*****p@school.cn: keep the first and last character of the part before @ and replace the rest with *. If that part has 2 characters or fewer, replace all of it with *. Return "invalid" if there is not exactly one @.
Starter file (write your code where it says pass # your code here):
def mask_email(email):
pass # your code here
# ---- tests ----
print(mask_email("sandeep@school.cn"))
print(mask_email("jo@mail.com"))
print(mask_email("a.b.chen@uni.edu"))
print(mask_email("no-at-sign.com"))
Expected output when your code is correct:
s*****p@school.cn **@mail.com a******n@uni.edu invalid
Hint
index to find the @, then slice before and after it.Model solution
def mask_email(email):
if email.count("@") != 1:
return "invalid"
at = email.index("@")
user, domain = email[:at], email[at:]
if len(user) <= 2:
return "*" * len(user) + domain
return user[0] + "*" * (len(user) - 2) + user[-1] + domain
# ---- tests ----
print(mask_email("sandeep@school.cn"))
print(mask_email("jo@mail.com"))
print(mask_email("a.b.chen@uni.edu"))
print(mask_email("no-at-sign.com"))
Task 3: Run-length encoding
Write encode(text) that compresses runs of repeated characters, e.g. "aaabccdddd" → "a3b1c2d4", and decode(code) that reverses it. Counts can have more than one digit ("x12"). Test that decode(encode(t)) == t.
Starter file (write your code where it says pass # your code here):
def encode(text):
pass # your code here
def decode(code):
pass # your code here
# ---- tests ----
print(encode("aaabccdddd"))
print(encode("xxxxxxxxxxxxy"))
print(decode("a3b1c2d4"), decode("x12y1"))
for t in ["", "a", "abc", "zzzzzzzzzzzzzzz", "aabbaa"]:
assert decode(encode(t)) == t
print("all round trips OK")
Expected output when your code is correct:
a3b1c2d4 x12y1 aaabccdddd xxxxxxxxxxxxy all round trips OK
Hint
Model solution
def encode(text):
if not text:
return ""
out = ""
current, count = text[0], 1
for ch in text[1:]:
if ch == current:
count += 1
else:
out += current + str(count)
current, count = ch, 1
return out + current + str(count)
def decode(code):
out = ""
i = 0
while i < len(code):
ch = code[i]
j = i + 1
while j < len(code) and code[j].isdigit():
j += 1
out += ch * int(code[i + 1:j])
i = j
return out
# ---- tests ----
print(encode("aaabccdddd"))
print(encode("xxxxxxxxxxxxy"))
print(decode("a3b1c2d4"), decode("x12y1"))
for t in ["", "a", "abc", "zzzzzzzzzzzzzzz", "aabbaa"]:
assert decode(encode(t)) == t
print("all round trips OK")
Learning objectives
By the end of this page you should be able to:
- Use positive and negative indexes to identify individual characters in a string.
- Construct slices s[start:stop:step] to extract substrings, remembering that the stop index is excluded.
- Manipulate strings by altering, concatenating and replacing, with methods such as upper(), strip(), find(), replace() and split().
- Explain why strings are immutable and how to build a new string instead.
Strings are sequences of characters
Each character has an index. Python counts from 0, so in s = "Dune", s[0] is "D" and s[3] is "e". Negative indexes count from the end: s[-1] is "e". len(s) is 4, so the last positive index is len(s) - 1. s[4] raises an IndexError.
Slicing: s[start:stop:step]
- Extracts the substring from start up to but not including stop:
"ShelfWise"[0:5]is"Shelf". The length ofs[a:b]isb - a. - Defaults: start 0, stop the end, step 1.
s[:3]first three,s[3:]from index 3 on,s[-4:]last four,s[::-1]reversed,s[::2]every second character. - Slices never raise IndexError: out-of-range bounds are clipped, so
"Dune"[1:99]is"une"and"Dune"[9:]is"".
Strings are immutable
You cannot change a string in place: s[0] = "J" gives a TypeError. Instead, build a new string and assign it: s = "J" + s[1:].
Manipulating strings
| Operation | Python | Example → result |
|---|---|---|
| Concatenate | a + b | "DUN" + "-" + "F" → "DUN-F" |
| Repeat | s * n | "-" * 5 → "-----" |
| Change case | upper() lower() title() | "dune".upper() → "DUNE" |
| Remove outer spaces | strip() | " Dune ".strip() → "Dune" |
| Find position | find(sub) | "Animal Farm".find(" ") → 6 (−1 if absent) |
| Replace | replace(old, new) | "978-0-14".replace("-", "") → "978014" |
| Split | split(sep) | "Orwell, George".split(", ") → ['Orwell', 'George'] |
| Test | in, startswith(), isdigit() | "978" in isbn → True / False |
| Count | count(sub) | "banana".count("a") → 3 |
A typical pattern: find, then slice
full_name = "George Orwell"
space = full_name.find(" ") # 6
first = full_name[:space] # "George"
surname = full_name[space + 1:] # "Orwell"
print(surname + ", " + first) # Orwell, George
In Java the same ideas use s.substring(a, b), s.charAt(i), s.indexOf(sub) and s.length(); the stop index is excluded there too.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. s = "COMPUTER". State the value of (a) s[0], (b) s[2:5], (c) s[-3:]. [3]
"C" [1]; (b) "MPU" (indexes 2, 3, 4) [1]; (c) "TER" [1].2. Outline the difference between s[3] and s[3:4] when s = "Dun". [2]
s[3] accesses a single index beyond the end, so it raises an IndexError [1]; s[3:4] is a slice whose bounds are clipped, so it returns the empty string "" [1].3. Trace the code and state the output. [3]
title = "the hobbit"
pos = title.find(" ")
code = title[pos + 1:pos + 4].upper()
print(pos, code, title.replace("t", "T"))
3 HOB The hobbiT [1].4. A program contains name = "dune" followed by name[0] = "D". Explain why this fails and construct a correct statement. [3]
name = "D" + name[1:] (or name = name.capitalize()) [1].5. Construct a function initials(full_name) that returns, for example, "A.L." for "Ada Lovelace". Assume exactly one space. [4]
space = full_name.find(" ") [1]; extract the first character full_name[0] [1]; extract the character after the space full_name[space + 1] [1]; concatenate with dots and return: return full_name[0] + "." + full_name[space + 1] + "." [1]. Accept split()-based solutions.6. Construct a function school_email(full_name, year) that returns, for ("Wei Zhang", 2027), the string "wzhang27@school.cn". [5]
full_name[0] [1]; surname slice full_name[space + 1:] [1]; last two digits of the year str(year)[2:] (or str(year)[-2:]) [1]; concatenation with "@school.cn" and .lower(), returned [1].