Unit 3, Lesson 3 of 5
Brainlag Plus

String handling

GCSE Computer Science, Writing code, 30 minutes

Indexing and slicing strings, counting and building strings in a loop, character codes with ord and chr, and splitting a sentence into words.

Indexes and slices

A string is a sequence of characters, and each has an index starting at 0, just like a list.

JobOCR styleAQA stylePython
Lengths.lengthLEN(s)len(s)
One characters.substring(i, 1)SUBSTRING(i, i, s)s[i]
Part of a strings.substring(start, count)SUBSTRING(start, end, s)s[start:end + 1]
Character to codeASC(c)CHAR_TO_CODE(c)ord(c)
Code to characterCHR(n)CODE_TO_CHAR(n)chr(n)

In Python, s[a:b] is the characters from index a up to, but not including, index b. So "banana"[0:3] is "ban" and "banana"[len("banana") - 2:] is "na". A slice that runs past the end is safe: "Li"[0:4] is just "Li".

The rest of this lesson and its 9 practice questions are in Plus.

Screen 1 of 4, free to read.

  • 9 exam-style questions, marked as you go, each with a worked solution
  • Anything you get wrong is saved to your flashcards