ICS3U Computer Science • Ontario Grade 11

Revision sheet: strings and built-in subprograms (ICS3U)

This sheet is not a summary of the strings chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks on indices, slices, string methods and the built-in subprograms of the course, and which precise gesture avoids each loss.

Most of these mistakes give no error message: a slice one character short, a method whose result is thrown away, a random call that never reaches its last value. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 8 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

A string is a row of characters numbered from 0, and it never changes: a slice, a method or a built-in function gives back a new value, lost unless it is stored or displayed, so every call is read by what goes in and what comes out.

Topics covered

  • String data type
  • Character index
  • Negative index
  • String slicing
  • String immutability
  • String methods
  • String concatenation
  • Type conversion
  • Built-in functions
  • Random number generator
  • Absolute value
  • Rounding and display formatting

The essentials

Two numberings of the same characters

  • • The characters of a string word have the indices 0 to len(word) - 1, from the left: word[0] is the first character, word[len(word) - 1] the last.
  • • A negative index counts from the end: word[-1] is the last character, word[-2] the one before it, and word[-len(word)] the first.
  • • A single index outside the string, such as word[len(word)], stops the program with an IndexError.
  • • len counts every character, spaces and punctuation included: len('Hi there!') is 9.
  • • A loop over the indices is for i in range(len(word)); a loop over the characters themselves is for ch in word.
K0-8E1-7Y2-6B3-5O4-4A5-3R6-2D7-1word = 'KEYBOARD': two numberings of the same characters8 characters
The K is word[0] and word[-8]; the D is word[7] and word[-1]. There is no word[8]: the last index is len(word) - 1 = 7.

When the position is fixed from the left, as in a code of fixed length, read it with a positive index: a negative index reaches another character as soon as the string grows.

Every call gives back a new value

  • • A slice word[a:b] gives back the characters of indices a to b - 1: the end is excluded, and the slice has b - a characters when it stays inside the string.
  • • A slice never raises an IndexError: word[5:50] stops at the end of the string, and word[20:] is the empty string.
  • • A method is called after a dot, word.upper(); a function takes its values in brackets, len(word). Both give back a value and change nothing.
  • • A string never changes: word = word.lower() stores the new string, while word.lower() alone computes it and throws it away. word[0] = 'k' is a TypeError.
  • • Read each call by what goes in, what comes out, its type and its range: count gives back an int, upper a str, randint(1, 6) a whole number from 1 to 6.

On a trace, write each value with its quotes when it is a string: '7' and 7 are not the same value.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

The built-in subprograms of the chapter

What goes in, and what comes out. Every example was run in Python 3, with word = 'KEYBOARD'.

CallGives backType of the result
len(s) the number of characters int

Example: len(word) is 8; len('') is 0.

s.upper(), s.lower() a copy in capital or lower-case letters str

Example: 'Grade 9'.upper() is 'GRADE 9': the digit and the space stay.

s.strip() a copy without the spaces at both ends str

Example: ' ok '.strip() is 'ok', 2 characters instead of 6.

s.replace(a, b) a copy where every a becomes b str

Example: '2025-2026'.replace('-', '/') is '2025/2026'; '1001'.replace('1', '7') is '7007'.

s.count(t), s.find(t) how many times t appears; the index of the first t, or -1 int

Example: word.count('O') is 1, word.find('B') is 3, word.find('Z') is -1.

abs(x) the distance from x to 0 int or float, like x

Example: abs(-12) is 12; abs(4 - 9.5) is 5.5.

round(x, n), round(x) x with n decimals; the nearest whole number float; int

Example: round(3.14159, 2) is 3.14; round(3.7) is 4.

max(a, b, ...), min(a, b, ...) the largest, the smallest of the values the type of the values

Example: max(3, -8, 5) is 5 and min(3, -8, 5) is -8.

random.randint(a, b), random.randrange(a, b) a whole number from a to b; from a to b - 1 int

Example: randint(1, 6) can give back 6, 6 values; randrange(1, 6) never does, 5 values.

str(x), int(s), format(x, '.2f') x as text; the number written in s; x as text with 2 decimals str; int; str

Example: str(25) + '%' is '25%', int('08') + 1 is 9, format(3.5, '.2f') is '3.50'.

s.upper() on its own line a new string, thrown away s unchanged result lost

Example: After word = 'key' and word.upper(), word still holds 'key', 3 lower-case letters.

What to do: Store the result: word = word.upper(), or display it: print(word.upper()).

Before using a call in a program, say its type: a str goes into + with another str, an int into a computation or a comparison with numbers.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. Reading the first character

1 mark per index on a trace, and every later value shifted by one

What not to write

“The first letter of word is word[1].”

What to write

“The first letter is word[0]; word[1] is the second one, and the last is word[len(word) - 1], or word[-1].”

Why: Indices count how many characters come before: the first character has none before it, so its index is 0.

2. The end of a slice

1 mark, and a program one character short that runs without any error

What not to write

“word[3:7] takes the characters from index 3 to index 7: 'BOARD'.”

What to write

“word[3:7] stops before index 7: 'BOAR', 7 - 3 = 4 characters. word[3:8], or word[3:], gives 'BOARD'.”

KEYBOARD012345678word[3:7] cuts at 3 and at 7: 'BOAR', 7 - 3 = 4 charactersword[7], the 'D', is not in the slice
The cuts 3 and 7 frame the green characters, BOAR; the D after cut 7, in red, is not part of word[3:7].

Why: The two numbers of a slice are cuts between characters: the slice runs from cut 3 to cut 7, and the character after cut 7 is left out.

3. Calling a method without storing its result

the whole question, since every later line works on the old string

What not to write

“code.upper() turns the code typed by the user into capitals.”

What to write

“code = code.upper(). On its own, code.upper() builds a new string and throws it away: code is unchanged, and no error says so.”

Why: A string never changes. Every method gives back a new string, which must be stored by = or displayed.

4. Simulating a die

1 to 2 marks, and a simulation that never shows one of the six faces

What not to write

“die = random.randrange(1, 6) gives a number from 1 to 6.”

What to write

“randrange(1, 6) gives 1 to 5 and never 6. Write random.randint(1, 6), which includes 6, or random.randrange(1, 7).”

123456123456randint(1, 6)randrange(1, 6)6 never6 values
randint(1, 6) can give back the six values; randrange(1, 6) stops at 5, and the 6 in red never comes out.

Why: randint(a, b) includes b; randrange(a, b) excludes b, like range(a, b).

5. A number inside a sentence built with +

the program stops on that line: everything after it is lost

What not to write

“level = 3, then print('Level ' + level) displays Level 3.”

What to write

“'Level ' + level is a TypeError: + never joins a str and an int. Write print('Level ' + str(level)), or print('Level', level).”

Why: + adds two numbers or joins two strings; Python refuses to guess which one is meant. Java accepts it and joins.

6. Comparing two numbers read by input()

1 to 2 marks, and a program wrong only when the numbers have different numbers of digits

What not to write

“a = input(), b = input(), then if a > b: compares the two numbers typed.”

What to write

“input() gives back strings, compared as text: '9' > '10' is True. Convert first: a = int(input()).”

Why: Text is compared character by character from the left, and '9' comes after '1'. The rules of string comparison are studied in Grade 12 (ICS4U).

7. Reaching the last character

the program stops: a run-time error in place of an answer

What not to write

“The last character of word is word[len(word)].”

What to write

“It is word[len(word) - 1], or word[-1]. word[len(word)] raises IndexError: string index out of range.”

Why: A string of 8 characters has the indices 0 to 7: the index 8 does not exist.

8. Displaying an amount of money

1 mark on an output to predict, and a receipt that reads 2.5 dollars

What not to write

“print(round(price, 2)) displays 2.50 for a price of 2.5.”

What to write

“round(2.5, 2) is still 2.5: a float keeps no zero at its end. format(price, '.2f') gives back the text '2.50'.”

Why: round computes a number; format builds the text of that number with the decimals asked for.

Which method to choose

Which tool for a question on a string?

Ask what the question wants back: one character, a piece, a transformed copy, a count, or a number.

  • If one character at a known position → an index: word[i] from the left, word[-k] from the end

    Example: the grade digit of a course code: code[3]

  • If several characters in a row → a slice word[a:b], with b the index just after the last character wanted

    Example: the minutes of '08:47': t[3:5], two characters

  • If a copy changed as a whole: case, spaces, one text replaced by another → a method, its result stored by =

    Example: name = name.strip().lower()

  • If something about every character: a count, a new string built from it → a loop over the characters, with an accumulator set before the loop

    Example: count the vowels: for ch in word, then if ch in 'AEIOU': n = n + 1

  • If a number written inside the text → a slice, then int() or float()

    Example: int('SCH3U'[3]) + 8 gives the grade, 11

A count of one given character needs no loop: word.count('O'). The loop is for a rule that a single method does not cover.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Predicting a slice or a call on a unit test

When to use it: « What is the value of ...? » or « What does this program print? » on indices, slices or methods

  1. 1 Write the string with its indices under the characters, from 0.
  2. 2 For a slice [a:b], list the indices a to b - 1, then copy those characters.
  3. 3 For a method, say what goes in and what comes out, and whether the result is stored.
  4. 4 Give the type of the result: a str with its quotes, an int or a float without them.
  5. 5 For an error, name it: IndexError, TypeError, with the line where the program stops.

Concluding sentence

“'KEYBOARD'[3:7] takes the indices 3, 4, 5 and 6: 'BOAR', a str of 7 - 3 = 4 characters.”

The trap: Copying the character at index b, the end of the slice, which is excluded.

Marking: A common split: 1 mark for the indices, 1 for the value with its quotes.

Writing a program that builds a string

When to use it: « Write a program that displays the code, the abbreviation, the masked number ... »

  1. 1 Set the accumulator before the loop: result = '' for a string, n = 0 for a count.
  2. 2 Loop over the characters, or over range(len(s)) when the position matters.
  3. 3 Add at the end of the accumulator with result = result + ...: the string grows by one piece per pass.
  4. 4 Convert every number that enters the string with str().
  5. 5 Trace the program on a short input and on an input where the rule changes, and check the length of the result.

Concluding sentence

“For 'KEY', the passes add 'K', 'E', 'Y' in turn, and result goes from '' to 'K', 'KE', then 'KEY', 3 characters.”

The trap: Writing result = '' inside the loop, which empties the string at every pass.

Marking: A common split: 1 mark for the accumulator, 1 for the loop, 1 for the output.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • The length of a slice

    A slice [a:b] inside the string has b - a characters: count them in your answer.

    'KEYBOARD'[2:5] must have 3 characters: 'YBO'. An answer of 4 characters has kept the end.

  • Every method stored or displayed

    Look at each line that calls a method: it must start with a name and =, or sit inside print().

    A line that reads text.strip() alone does nothing: write text = text.strip().

  • The same type on both sides of +

    For each +, check that the two sides are both str or both numbers.

    'Room ' + 12 stops the program; 'Room ' + str(12) gives 'Room 12'.

  • The two ends of a random call

    Write the smallest and the largest value a random call can give back, and compare them with the specification.

    A score from 0 to 100 is randint(0, 100): 101 values. randrange(0, 100) stops at 99.

The typical problem, taken apart

A school username built from a name

A school builds each username from the first letter of the first name followed by the last name, in lower case, and keeps at most 8 characters. The names are typed by hand, so spaces may surround them.

Write the program, then trace it for Priya Ramanathan. What does it give for Li Wu?

Python
first = input('First name: ').strip()
last = input('Last name: ').strip()
username = (first[0] + last).lower()
username = username[:8]
print(username)

Step 1

strip() on each input: first = 'Priya' and last = 'Ramanathan', whatever spaces were typed around them.

Why

A space typed before the first name would otherwise become first[0], and the username would start with a space.

Step 2

first[0] + last is 'P' + 'Ramanathan' = 'PRamanathan', 11 characters; lower() gives back 'pramanathan', and = stores it in username.

ExpressionValuefirst[0]'P'first[0] + last'PRamanathan'(first[0] + last).lower()'pramanathan'username[:8]'pramanat'Each step gives back a new string

Why

The first letter is at index 0. The result of lower() is kept by the assignment, since the string itself never changes.

Step 3

username[:8] keeps the indices 0 to 7: 'pramanat'.

Why

The slice [:8] gives at most 8 characters, and its end, 8, is excluded: 8 - 0 = 8 characters.

Step 4

For Li Wu: first[0] + last is 'LWu', lower() gives 'lwu', and username[:8] is still 'lwu', 3 characters, without any error.

Why

A slice stops at the end of a short string. A single index such as username[7] would raise an IndexError here: the slice is the right tool for « at most 8 ».

The conclusion, written out

“For Priya Ramanathan, the program prints pramanat, 8 characters; for Li Wu, it prints lwu.”

The classic mistake on this problem: Writing (first[0] + last).lower() on its own line, without username =, then printing the old value: the lower-case copy is lost.

Learn by heart

  • • Indices run from 0 to len(s) - 1; s[-1] is the last character.
  • • s[a:b] stops before b and has b - a characters; a slice never raises an IndexError.
  • • A string never changes: s = s.upper(), never s.upper() alone.
  • • + joins two str or adds two numbers: 'Total: ' + str(n).
  • • randint(a, b) includes b; randrange(a, b) stops at b - 1.
  • • input() gives back a str: int() before comparing or computing.
  • • round computes, format(x, '.2f') displays two decimals.
  • • abs gives a distance: it removes a sign, it does not repair a count.

Frequently asked questions

Why does my string not change after I call upper() in Python?

Because a string in Python can never be modified. The upper method builds a new string in capital letters and gives it back; if no assignment stores it, that new string is lost and the variable keeps its old value. Write the variable name, an equals sign, then the call, so that the variable now holds the new string.

Why does a Python slice not include its last index?

The two numbers of a slice are cuts between characters, not characters. A slice from 3 to 7 starts at the cut before index 3 and stops at the cut before index 7, so it holds the characters 3, 4, 5 and 6, four characters. That rule gives a slice of b minus a characters and lets two slices meet without overlap.

What is the difference between randint and randrange in Python?

randint takes two whole numbers and can give back both of them: randint with 1 and 6 gives any number from 1 to 6, like a die. randrange stops before its second number, as range does: randrange with 1 and 6 gives 1 to 5 only. To include the upper end with randrange, add one to it.

Why do I get a TypeError when I join text and a number with plus in Python?

Because the plus sign adds two numbers or joins two strings, and Python refuses to guess which one you mean when one side is text and the other a number. Convert the number to text with str first, or give print several values separated by commas, which prints them with a space between them.

Why does Python say that 95 is greater than 120?

Because the two values are strings, usually read by input, and strings are compared as text, character by character from the left. The first characters are 9 and 1, and 9 comes after 1, so the text 95 counts as larger. Convert the values with int or float before comparing them, and the numbers are compared by their values.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Strings and built-in subprograms, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 12 corrected exercises
  • 120 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Revision sheet published at www.letuteurscientifique.ca/en/fiches/ics3u-strings-built-in-subprograms. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session.

Site by Studio Squalli