Home › Theme B › B2 › B2.1 › B2.1.2

B2.1.2 Working with substrings

SL + HLCommand term: Construct

1. 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 =
s[::]   or one index s[]
Try:
→

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 =
Method:
→
After the call, 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.

isbn =

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: is the slice right?

True or false? Watch out for the stop index: it is not included.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 1, task 2. ShelfWise needs shelf codes, author names in catalogue order, clean ISBNs and the joining year from a member ID. Download the starter, complete the five functions with substring operations, run it, and compare with the expected output.

Expected output

DUN-F ANI-F Orwell, George 9780141036144 True False 2028

Check my code

    Later: in B2.1.3 these functions get try/except so a bad member ID cannot crash ShelfWise; in Sprint 1, task 3 they join 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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_1_2_average.py
    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
    File: b2_1_2_average_solution.py
    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"))
    
    Moderate

    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):

    File: b2_1_2_moderate.py
    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
    Use index to find the @, then slice before and after it.
    Model solution
    File: b2_1_2_moderate_solution.py
    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"))
    
    Challenging

    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):

    File: b2_1_2_challenging.py
    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
    In decode, after each letter keep reading characters while they are digits.
    Model solution
    File: b2_1_2_challenging_solution.py
    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:

    1. Use positive and negative indexes to identify individual characters in a string.
    2. Construct slices s[start:stop:step] to extract substrings, remembering that the stop index is excluded.
    3. Manipulate strings by altering, concatenating and replacing, with methods such as upper(), strip(), find(), replace() and split().
    4. 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 of s[a:b] is b - 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

    OperationPythonExample → result
    Concatenatea + b"DUN" + "-" + "F" → "DUN-F"
    Repeats * n"-" * 5 → "-----"
    Change caseupper() lower() title()"dune".upper() → "DUNE"
    Remove outer spacesstrip()" Dune ".strip() → "Dune"
    Find positionfind(sub)"Animal Farm".find(" ") → 6 (−1 if absent)
    Replacereplace(old, new)"978-0-14".replace("-", "") → "978014"
    Splitsplit(sep)"Orwell, George".split(", ") → ['Orwell', 'George']
    Testin, startswith(), isdigit()"978" in isbn → True / False
    Countcount(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]

    (a) "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"))
    pos = 3 [1]; title[4:7] is "hob", so code = "HOB" [1]; every "t" is replaced: 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]

    Strings are immutable / cannot be changed in place [1], so item assignment raises a TypeError [1]. Correct: 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]

    Locate the space, e.g. 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]

    Find the space / split the name [1]; first letter of the first name 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].