Indexing and slicing strings, counting and building strings in a loop, character codes with ord and chr, and splitting a sentence into words.
What you will learn
- Read characters by index and take slices
- Count characters with a loop
- Build a new string one character at a time
- Use ord and chr to work with character codes
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".
Leaving out a number means "from the start" or "to the end": "banana"[1:] is "anana" and "banana"[:2] is "ba". To drop the first and last characters, use s[1:len(s) - 1]: "melon"[1:4] is "elo".
Python strings have methods for case: "Ada".upper() is "ADA" and "Ada".lower() is "ada". They work on one character too: name[0].upper() is the first letter as a capital. Numbers must be turned into text with str() before slicing or joining: str(2031)[2:] is "31".
The rest of this lesson and its 9 practice questions are locked.
In this lesson
- Indexes and slices
- Loop through the characters
- Character codes
- Try it: Initials
9 practice questions, marked as you go; about 30 minutes in all.
Key terms
Strictly, Caesar cipher
In this unit: Writing code
Write real Python that runs against tests: functions, validation and logins, strings, lists and 2D lists, records, and completing and refining a program.