Card 14: Strings

Module 6: Advanced Techniques

1 The Hook

Think of a String like a bead necklace.

  • Indexing: Picking ONE bead.
  • Slicing: Cutting a SECTION of the necklace.

Computers start counting from 0, not 1!

2 Worked Example

Extracting parts of a secret code.

# P=0, Y=1, T=2, H=3, O=4, N=5
code = "PYTHON"
# Index [0] gets First
print(code[0]) # Prints "P"
# Slice [0:3] gets 0, 1, 2 (Stops BEFORE 3)
print(code[0:3]) # Prints "PYT"

Power Up: Left & Right

You might see exam questions ask for LEFT or RIGHT characters.

# LEFT(3) -> First 3

text[:3] // Start at 0, stop at 3

# RIGHT(3) -> Last 3

text[-3:] // Start at -3, go to end

PREDICT

What is the output?

word = "GALAXY"
print(word[1])

Remember: G is 0, A is 1...

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Last Letter

1. The code currently prints the FIRST letter [0].
2. Change it to print the LAST letter using [-1].
3. Run it to see "n".

> _
SILVER (FIX)

🥈 Off by One Error

1. The goal is to extract "Code" (first 4 letters).
2. The code uses [0:3] which only gives indices 0, 1, 2.
3. Fix it to include index 3. Hint: Stop number is NOT included!

> _
GOLD (MAKE)

🥇 User Gen

1. Ask for first name.
2. Ask for last name.
3. Create username: First 3 letters of first + First 2 of last.
4. Print it in UPPERCASE.

> _