String handling
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.
| Job | OCR style | AQA style | Python |
|---|---|---|---|
| Length | s.length | LEN(s) | len(s) |
| One character | s.substring(i, 1) | SUBSTRING(i, i, s) | s[i] |
| Part of a string | s.substring(start, count) | SUBSTRING(start, end, s) | s[start:end + 1] |
| Character to code | ASC(c) | CHAR_TO_CODE(c) | ord(c) |
| Code to character | CHR(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