University of Toronto · FACULTY OF COMPUTER SCIENCE

CSC108H1 Chap.7 Strings: Indexing, Slicing and Methods

- one subject, every graph, every model, every mark
6 Chapters4-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 7 of 10 · CSC108H1

Strings: Indexing, Slicing and Methods

Text as a sequence

A string is a sequence of characters. Each character has an index counted from 0 on the left and from -1 on the right, and a slice collects the characters from one index onward, stopping just before a second index. A third number in a slice sets the stride.

Methods and the help sheet

Methods are functions that belong to a type and are called with dot notation.

String methods always return a new value and never change the original. Quizzes in the course supply help entries for the functions and methods you need, so reading those entries accurately is part of the skill.

How strings are assessed

Worksheet 12 asks you to build a target string from indices, to fill a table of slice values and to pick out expressions using in that produce False.

Worksheet 13 asks which expressions produce a given result using a printed help sheet for str, and notes that the sheet is similar to the one given on the midterm test. Both reward reading carefully rather than memorising.

In this chapter

What this chapter covers

  • 01

    Quotes, the empty string and len

  • 02

    Concatenation, repetition and conversion

  • 03

    Positive and negative indices

  • 04

    Slices, omitted ends and strides

  • 05

    String methods return new strings

  • 06

    Reading help entries for find, count and strip

Worked example · free

Slice a string using both index directions

Q [4 marks]. AskSia-authored practice. With s = 'maple', give s[1:4], s[-1] and s[::2], and explain why the first answer has three characters. The marks shown are an AskSia study allocation, not an official University marking scheme.
Figure 7.1.Figure 7.1. The five boxes hold the characters of the string maple, with positive indices above and negative indices below. The red bracket marks s[1:4], which starts at index 1 and stops before index 4, giving the three characters apl.maple01234-5-4-3-2-1indexnegatives[1:4] is 'apl'
Figure 7.1. The five boxes hold the characters of the string maple, with positive indices above and negative indices below. The red bracket marks s[1:4], which starts at index 1 and stops before index 4, giving the three characters apl.
  • 2s[1:4] takes indices 1, 2 and 3, giving 'apl'; its length is 4 - 1 = 3.
  • 1s[-1] is the last character, 'e'.
  • 1s[::2] takes indices 0, 2 and 4, giving 'mpe'.
Counting from 0, maple has m, a, p, l, e at indices 0 to 4. The slice from 1 stops before 4, so it is 'apl'. The last character is 'e' at -1, and a stride of 2 from the start picks m, p and e for 'mpe'.
Sia tip — Write the index under every character before slicing; the end index of a slice is the first position you do not take.
Glossary

Key terms

Index
Where a character sits in a string, numbered from 0 at the left or from -1 at the right.
Slice
A substring that begins at one index and stops just before another.
Stride
The optional third slice number that sets the step between characters taken.
Method
A function attached to a type, called on a value using dot notation.
Concatenation
Joining two strings end to end with the + operator.
Empty String
The string with no characters at all, written as two quotes with nothing between them.
FAQ

Strings: Indexing, Slicing and Methods FAQ

Why does s[len(s)] raise an error?

Indices start at 0, so the last character of s is at len(s) - 1. Asking for position len(s) points one past the end, where no character exists, and Python raises an IndexError. Slices are more forgiving, but single indices are not.

Does calling upper change the original string?

No. String methods return a new string and leave the original untouched. To keep the result, assign it to a variable, and to replace the old text, reassign the same name to the value the method returned.

How do I find the second occurrence of a character?

Call find a second time with a start position one past the first result, as in s.find(c, s.find(c) + 1). Starting exactly at the first index returns that same index again, which is a common wrong answer.

What does a negative stride do in a slice?

It walks through the string from right to left. With the start and end left out, a stride of -1 visits every character backwards, so the slice reverses the string. Larger negative strides skip characters while moving backwards.

Why does 'Room ' + 101 raise an error?

Because + joins two strings or adds two numbers, but cannot combine a string with an int. Convert the number first with str, as in 'Room ' + str(101), which gives the string 'Room 101'. The reverse conversion uses int on a string of digits.

Study strategy

Exam move

Pick three strings of different lengths, including one with spaces, and write their index tables with positive and negative indices. Set yourself ten slices and five method calls on them, answer on paper, then check in the shell. Practise with only the help sheet beside you, reading each entry's return type before answering. Time yourself on one full worksheet's worth of questions to build speed for the quizzes.

Include the empty string in at least two of your questions, since the is-methods treat it specially, and include one negative stride.

Working through Strings: Indexing, Slicing and Methods in CSC108H1? Sia is AskSia’s AI Computer Science tutor — ask any CSC108H1 Strings: Indexing, Slicing and Methods question and get a clear, step-by-step explanation grounded in how CSC108H1 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 21 of your University of Toronto subjects - and 1,000+ Bibles across every Australian university.
Sia - your CSC108H1 tutor, unlimited, worked the way the exam marks it
The full 4-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works