IB COMPUTER SCIENCE | B2.1.2 Substrings

Lesson objective

Construct Python programs that locate and extract substrings, then alter, concatenate or replace text using accurate indexes and string methods.

Learn

B2.1.2 | SUBSTRINGS

01 | A SMALL PART OF A BIGGER STRING

A booking code might contain a school prefix, a year and a reference number. A message might contain a name you want to replace. A program often needs only part of the text rather than the complete string.

A substring is a contiguous sequence of characters within a string. Extracting a substring produces the required text; manipulating it can involve changing case, replacing content or joining it to other text.

This common SL/HL lesson uses Python. We will build from individual character positions to complete programs that locate, extract and alter text. Watch the difference between a position and a length, and between creating a new string and changing the original.

02 | INDEXES START AT ZERO

An index identifies a character’s position. Python uses zero-based indexing: the first character has index 0, the second index 1, and so on. The word ROBOT has five characters but its last positive index is 4.

index 0 R -5
index 1 O -4
index 2 B -3
index 3 O -2
index 4 T -1
text = "ROBOT"
print(text[0])  # R
print(text[4])  # T
print(len(text))  # 5

len returns the number of characters, not the last index. For a nonempty string, the last non-negative index is len(text) - 1. Spaces and punctuation count as characters too.

03 | NEGATIVE INDEXES COUNT FROM THE END

text = "ROBOT"
print(text[-1])  # T
print(text[-2])  # O

Index −1 identifies the final character, −2 the one before it, and so on. This is useful when the length can vary, such as finding the last character of a nonempty code.

Negative indexing does not reverse the string. It provides another way to refer to a position. In ROBOT, text[4] and text[-1] both produce T.

An empty string has no character at index 0 or −1. Check that a string is nonempty before indexing when empty input is possible.

04 | SLICING: INCLUDE THE START, EXCLUDE THE STOP

text = "ROBOTICS"
part = text[1:4]
print(part)  # OBO
index 0 R -8
index 1 O -7
index 2 B -6
index 3 O -5
index 4 T -4
index 5 I -3
index 6 C -2
index 7 S -1

A slice uses text[start:stop]. It includes the character at start and continues up to, but not including, stop. Here it includes indexes 1, 2 and 3, giving OBO.

The stop value is an exclusive boundary, not the number of characters to extract. For an ordinary forward slice with suitable in-range bounds, its length is stop - start.

Think of a stop at 4 as “stop before index 4”. Writing text[1:3] would extract only indexes 1 and 2, giving OB.

05 | TURN A START AND LENGTH INTO A SLICE

A requirement might say “take three characters starting at index 2”. Python wants a stopping position, so calculate stop = start + length. Do not put the length directly after the colon.

text = "ROBOTICS"
start = 2
length = 3
stop = start + length
part = text[start:stop]
print(part)  # BOT
Requested start Requested length Python slice Result
0 3 text[0:3] ROB
2 3 text[2:5] BOT
5 3 text[5:8] ICS

If a question or another notation numbers characters from 1, convert deliberately: its position 1 corresponds to Python index 0. This page consistently uses Python indexes.

06 | OMITTED BOUNDS AND NEGATIVE BOUNDS

text = "ROBOTICS"
print(text[:3])   # ROB
print(text[5:])   # ICS
print(text[:])    # ROBOTICS
print(text[-3:])  # ICS
print(text[:-3])  # ROBOT

Omitting start means begin at the start of the string; omitting stop means continue to its end for these forward slices. Negative bounds count from the end, while the stop remains exclusive.

text[-3:] means the last three characters. text[:-3] means everything before those last three characters. These look similar but extract different parts.

07 | EMPTY SLICES AND OUT-OF-RANGE INDEXES

text = "ROBOT"
print(repr(text[3:3]))   # ''
print(repr(text[4:2]))   # ''
print(text[2:100])      # BOT
# text[100] would raise IndexError

For a forward slice with the default step, equal start and stop or a start beyond stop produces an empty string. Slice bounds are clipped to the available range, so text[2:100] returns the available characters from index 2.

Single-character indexing behaves differently: text[100] raises IndexError because no such character exists. A slice that runs safely is not necessarily correct: silently receiving too few characters may violate a code-format requirement.

repr displays a representation with quotes, helping you see an empty string or a space that would otherwise be difficult to notice.

08 | INTERACTIVE: SEE EXACTLY WHAT THE SLICE TAKES

Change the text and bounds, then predict the result before checking. Blank bounds mean omitted bounds. The boxes show zero-based indexes and negative indexes; pink marks included characters. This explorer uses the default forward step of 1.

Use up to 40 Unicode code points. Spaces count; some visible symbols can consist of several code points.

09 | FIND THE POSITION BEFORE EXTRACTING

message = "Welcome Maya"
position = message.find("Maya")
print(position)  # 8
name = message[position:position + 4]
print(name)  # Maya

str.find searches for a substring and returns the index where its first occurrence starts. It returns an integer position, not the matching text. The search is case-sensitive: Maya and maya differ.

Combine the found position with the substring length to calculate its end. This is more adaptable than guessing a fixed position when a prefix can vary.

Do not immediately slice using a find result unless you know it succeeded. A missing match returns −1, which is also a valid negative index or slice bound in Python.

10 | HANDLE A MISSING MATCH EXPLICITLY

message = "Welcome Maya"
position = message.find("Leo")

if position == -1:
    print("Name not found")
else:
    name = message[position:position + len("Leo")]
    print(name)

The guard distinguishes failure from a valid position. A match at index 0 is valid, so if position: is not an appropriate found/not-found test: zero is false in a truth test, while −1 is true.

The related index method returns a position when found but raises ValueError when absent. find is convenient when you plan to test a −1 result. Choose a method whose failure behaviour your program handles.

11 | LOCATE A DELIMITER

record = "Maya:Robotics"
separator = record.find(":")

if separator == -1:
    print("Missing separator")
else:
    name = record[:separator]
    activity = record[separator + 1:]
    print(name)      # Maya
    print(activity)  # Robotics

A delimiter separates parts of structured text. Find its index, take everything before it and then everything after it. Adding 1 skips this one-character delimiter.

For a multi-character delimiter, advance by len(delimiter), not always by one. If several delimiters occur, decide whether the first, last or all are meaningful. The format rules determine the correct extraction.

This example handles a missing colon but permits empty parts. If both fields are required, check that the separator is neither first nor last.

12 | FIRST MATCH, LAST MATCH AND MEMBERSHIP

filename = "report.final.txt"
position = filename.rfind(".")
print(filename[:position])      # report.final
print(filename[position + 1:])  # txt
print("final" in filename)     # True

rfind gives the start of the last occurrence, or −1 if absent. It can suit an illustrative last-dot split. A complete file-path parser has more rules; this example assumes a simple filename with a final extension.

Use in when you only need to know whether text occurs. Use find or rfind when you also need its position. Both position searches are case-sensitive.

A known prefix or suffix can be checked with startswith or endswith. If an extension is meant to be exactly .txt, a suitable suffix test is clearer than searching for txt anywhere.

13 | STRINGS ARE IMMUTABLE

word = "cat"
# word[0] = "b" would raise TypeError
word = "b" + word[1:]
print(word)  # bat

Immutable means an existing string object’s contents cannot be altered in place. To change part of the text, construct a new string and, if needed, assign the name to that new value.

The assignment word = ... is allowed: it rebinds the name. It is different from trying to assign to one character inside the existing string.

String methods such as replace and upper return new strings. If you ignore that returned value, the original name still refers to its previous text.

14 | ALTER A SUBSTRING BY REBUILDING THE TEXT

message = "Hello Maya!"
start = 6
stop = 10
replacement = "Leo"
updated = message[:start] + replacement + message[stop:]
print(updated)  # Hello Leo!
print(message)  # Hello Maya!

Keep the prefix before start, insert the replacement, then keep the suffix beginning at stop. Since the removed slice excluded stop, the suffix must begin at stop rather than stop + 1.

The replacement can have a different length from the removed text. The original remains unchanged because the expression constructs a new string.

To insert without removing, use the same boundary for prefix and suffix. To delete a slice, join the prefix and suffix with an empty replacement.

15 | CONCATENATION: CONTROL THE SPACES

first = "Maya"
last = "Chen"
full_name = first + " " + last
print(full_name)  # Maya Chen

places = 2
message = "Places: " + str(places)
print(message)  # Places: 2

Concatenation joins strings in order. Python does not automatically insert a space when you use +. first + last would produce MayaChen. Include separators deliberately.

Concatenating a str and an int directly raises TypeError, so convert the number to text when constructing this message. This conversion is for presentation, not numeric calculation.

An f-string such as f"Places: {places}" is another presentation option: braces insert a value. The explicit + examples make each substring and separator visible.

16 | REPLACE MATCHES WITH A METHOD

text = "red blue red"
updated = text.replace("red", "green")
first_only = text.replace("red", "green", 1)
print(updated)     # green blue green
print(first_only)  # green blue red
print(text)        # red blue red

replace(old, new) returns a new string with all non-overlapping occurrences replaced. An optional count limits replacements from the left. Count 0 replaces none. Matching is case-sensitive.

replace works on substrings, not automatically on complete words. Replacing cat in concatenate would also affect that larger word. If the requirement concerns words, you need rules that identify word boundaries.

Replacing with "" removes matching text. If old does not occur, the returned string has the same text as the original.

17 | INTERACTIVE: FIND AND REPLACE

Enter text, a nonempty search substring and its replacement. A blank replacement deletes matches. A blank limit means all matches; a whole-number limit from 0 to 10 restricts how many are replaced. Predict the first position and result before checking.

Use up to 80 code points in each text field. The nonempty search restriction keeps this activity focused on replacing existing text.

18 | CHANGE CASE AND REMOVE EDGE WHITESPACE

raw = "  Maya Chen  "
cleaned = raw.strip()
print(repr(cleaned))        # 'Maya Chen'
print(cleaned.upper())     # MAYA CHEN
print(cleaned.lower())     # maya chen
print(repr(raw))           # '  Maya Chen  '

strip with no argument removes leading and trailing whitespace, not spaces within the name. upper and lower create case-transformed text. Assign the result if a later step should use it.

Be careful when a requirement preserves names or case-sensitive identifiers: normalising a copy for comparison does not always justify changing stored display text.

strip(".txt") does not remove a literal extension. Its argument is a set of characters removable from either end. For a known suffix, check endswith and slice off its known length, or use an appropriate exact-suffix method.

19 | OPTIONAL SLICE STEP: SKIP OR REVERSE

text = "ROBOTICS"
print(text[::2])   # RBTC
print(text[::-1])  # SCITOBOR

The full slice form is text[start:stop:step]. With step 2, take every other character: indexes 0, 2, 4 and 6 of ROBOTICS give RBTC. With step −1 and omitted bounds, reverse the string.

A step of zero is invalid. Negative-step bounds have different defaults from forward slicing, so do not assume the earlier positive-step length shortcut applies. The interactive slicer deliberately uses step 1.

These are useful extensions; accurate extraction and manipulation of the required substring remains the main objective.

20 | WORKED PROGRAM: EXTRACT A STRUCTURED CODE

code = "AIG-2027-0042"

if (len(code) == 13 and code[3] == "-" and code[8] == "-"):
    school = code[:3]
    year_text = code[4:8]
    reference = code[9:]
    label = school + " / " + year_text + " / " + reference
    print(label)
else:
    print("Unexpected code structure")

For the shown input, the output is AIG / 2027 / 0042. The reference remains text so its leading zeros are preserved. The delimiters are omitted by the chosen boundaries.

The length check is 13. Count the parts: AIG is 3, the two hyphens add 2, the year 4 and the reference 4, giving 13 characters. Valid indexes end at 12.

This checks the length and delimiter positions only. It does not prove that the school is recognised, the year digits are valid or the reference exists. Distinguish structural checks from a complete validation policy.

21 | WORKED PROGRAM: ALTER A FOUND NAME

def rename_first(message, old_name, new_name):
    position = message.find(old_name)
    if position == -1:
        return message
    stop = position + len(old_name)
    return message[:position] + new_name + message[stop:]

original = "Maya meets Maya"
updated = rename_first(original, "Maya", "Leo")
print(updated)   # Leo meets Maya
print(original)  # Maya meets Maya

The local position locates the first match. Its length determines stop. The function returns a new string consisting of prefix, new name and suffix. The caller stores it in updated.

Assume old_name is nonempty for this task. This is a first-substring replacement, not a parser that recognises people’s complete names in arbitrary sentences. The requirement and input assumptions matter.

22 | TRACE THE BOUNDARIES

Expression with text = "ROBOTICS" Characters / reasoning Result
text[0:3] Indexes 0, 1, 2 ROB
text[2:5] Indexes 2, 3, 4 BOT
text[-3:] Last three characters ICS
text[3:3] No characters before the same boundary Empty string
text[:2] + "X" + text[5:] Keep RO; replace BOT; keep ICS ROXICS

Use a character/index diagram before calculating a difficult expression. In a trace, keep the original text and derived values separate, and check whether a new result was actually assigned.

23 | CONSTRUCT A PROGRAM: A MEMBER LABEL

Input a record in the form name:group, such as Maya:A. Locate the colon and check that both parts are nonempty. Extract the name and group. Require the group to contain exactly one character, then produce a label with the name, a space, and the uppercased group in brackets: Maya (A).

Keep the original input available and handle a missing colon. For this task assume names cannot contain a colon and reject extra colons. Build the result from substrings rather than fixed name positions.

Reveal one possible solution
record = input("Enter name:group: ")
separator = record.find(":")

if record.count(":") != 1:
    print("Use exactly one colon")
else:
    name = record[:separator].strip()
    group = record[separator + 1:].strip()
    if name == "" or len(group) != 1:
        print("Enter a name and one group character")
    else:
        label = name + " (" + group.upper() + ")"
        print(label)

count counts occurrences of the colon. The initial exactly-one check also handles a missing separator. This example only checks one group character; a permitted set of group letters would need another rule. Some Unicode case transformations can expand a character, so a specification requiring exactly one uppercase group letter should restrict permitted values accordingly.

24 | COMMON MISTAKES

Mistake Correction
The first index is 1 Python starts at 0.
The stop is included The default forward slice excludes stop.
The stop is a length For start + length extraction, calculate stop = start + length.
find returns the text It returns the starting index, or −1 if absent.
if position means found Position 0 is valid; explicitly test the −1 failure result.
replace changes the original object It returns new text; store the result if needed.
Concatenation inserts spaces Include separators explicitly.
A successful slice proves the format is valid Clipped bounds may hide incomplete data.

25 | TEST WITH PURPOSE

Use normal text, a match at the beginning, a match at the end, a missing match, repeated matches and empty input where permitted. For slices, test equal bounds, a boundary at len(text) and negative indexes.

For replacement, check a different-length replacement, an empty replacement and count 0 or 1. Confirm whether the original must remain available and whether matching should be case-sensitive.

Construct means produce a program satisfying the stated task, not only a description of the slice notation. Test its inputs, derived boundaries and final output against the requirement.

26 | CONNECT TO WHAT COMES NEXT

You can now identify positions, extract substrings, locate delimiters, construct altered text and combine string methods in complete programs. Keep checking where a substring starts, where it stops and whether you used the returned string.

Errors such as a missing index, unsuitable conversion or invalid operation need a deliberate response. The next lesson introduces common exception-handling techniques.

MATCH THE STRING IDEA TO ITS ROLE

Terminology

Terminology

Substring

A contiguous sequence of characters within a string.

Index

A position identifying a character in a string.

Zero-based indexing

Numbering the first character as index 0.

Negative index

A position counted from the end, with −1 referring to the last character.

Slice

Extraction using start, stop and optionally step boundaries.

Start bound

The first included position in an ordinary forward slice.

Exclusive stop

The boundary before which a slice stops; the character at stop is excluded.

Length

The number of characters in a string or substring.

Empty string

A string containing no characters, written "" or ''.

Default step

The forward slice step of 1 when step is omitted.

Concatenation

Joining strings in sequence.

Delimiter

A character or substring separating parts of structured text.

find

A str method returning the first match position or −1 when absent.

rfind

A str method returning the last match position or −1 when absent.

index method

A str search method raising ValueError if a match is absent.

Membership test

Using in to obtain whether a substring occurs.

Case-sensitive matching

Treating uppercase and lowercase characters as different.

Immutable string

A string whose existing character contents cannot be changed in place.

Rebinding

Associating a name with a new value rather than altering the old string.

replace

A str method returning a string with selected non-overlapping matches replaced.

Replacement count

An optional limit on how many matches replace changes from the left.

strip

A str method removing edge whitespace by default, or characters from a specified set.

upper

A str method returning an uppercase transformation.

lower

A str method returning a lowercase transformation.

startswith

A str method testing whether text begins with the specified prefix.

endswith

A str method testing whether text ends with the specified suffix.

Guard condition

A check preventing an operation from being used under unsuitable conditions.

IndexError

An exception raised by an unavailable single-character string index.

Representation

A display such as repr output that exposes quotes and otherwise hidden characters.

Off-by-one error

A boundary error that includes or excludes one extra position.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe Python indexing?
2. For text="ROBOTICS", which are correct?
3. Which extract the last three characters of ROBOTICS?
4. Which distinguish slices from indexing?
5. Which describe find?
6. Which construct a replacement of text[start:stop]?
7. Which describe Python strings?
8. Which describe replace?
9. Which are correct about presentation?
10. Which improve program testing?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Construct a slice extracting three characters from index 2 of "ROBOTICS".

2. Explain why text[1:4] extracts three characters rather than four.

3. Construct a program extracting the parts of "Maya:Robotics".

4. Explain why a find result should be checked against −1.

5. Construct a first-occurrence replacement using slices.

6. Trace the three replacement expressions in section 16.

7. Explain why word[0]="b" fails but word="b"+word[1:] works.

8. Construct a label containing a name, space and number of places.

9. Explain the difference between text[-3:] and text[:-3].

10. Construct code to find the final extension in "report.final.txt" under the simple-filename assumption.

11. Explain why a safe slice is not a complete validation check.

12. Describe tests for the member-label program.

CONSTRUCT IT | AN ACTIVITY RECORD

Input a record such as Robotics|Maya. Require exactly one vertical-bar delimiter and nonempty trimmed parts. Extract the activity and name. Construct Maya - ROBOTICS using an uppercase activity copy, keeping the original available. Test a missing delimiter, an empty part and repeated delimiters.

Reveal an approach

Check record.count("|") == 1. Find its position, then extract record[:position].strip() and record[position+1:].strip(). Reject empty parts; otherwise join name + " - " + activity.upper(). Do not assume the name always begins at a fixed index.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B2.1.2 Substrings is coming soon. Complete the matching task and written questions in your exercise book.