Lesson 7 of 16 · 50 min · UG / professional
String index, methods and immutability
You cannot change the third character of a PAN-like code in place. You build a new string. Index 0 is the first character; methods like upper and replace are how filing keys get clean.
Class notice message
Strings are text you can shape.
You will be able to
- ✓ Read the first character with index 0
- ✓ Use len, upper, lower, replace, split
- ✓ Treat strings as immutable
Index 0, length, methods
The first character of a code is code[0]. len is how many characters. .upper() / .lower() make a filing key. .replace() fixes a known hyphen habit. .split() turns a line of tokens into a list. Negative indices and slices (code[0:4]) are laptop spellings — this sandbox uses [0] and len.
Out-of-range index errors on a laptop; out-of-range slices are often empty. Know the difference so you do not ‘fix’ a PIN check by slicing blindly.
You cannot assign to a character
Strings cannot be changed in place. To ‘fix’ the first letter you build a new string. That immutability is why two functions can share a name string without one of them vandalising the ID card spelling. Mutate a list of characters only if you meant a list — usually you did not.
Laptop: slice and last character
word = "Python" print(word[0:2], word[-1], word[4:]) # word[0] = "J" # TypeError — immutable
Words that matter
- Index
- Position. First character is 0.
- Immutable
- Cannot change in place — build a new string.
- Method
- A function that belongs to this value, like .upper().
Common mistakes
Avoid: Assigning to name[0] to capitalise a student name.
Do this: name = name[0].upper() + name[1:] on a laptop, or upper() the filing key only.
Run it step by step
Each box is a real program. Press Run, change a number, Run again — the output must follow your code.
1. Step 1 — first character and length
PIN-like code: first digit and how many characters.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
2. Step 2 — filing key
Display stays mixed case; key is lower.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Example program — Split a subject, then upper a department
Methods return new strings (or a list). The original stays.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Lowercase filing key
raw = "Labs". Print the lowercase form so labs appears.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.