← Back to course
Code Crew G4 / Week 05 / Monday
1/6
Week 05 Β· Strings up close

Monday

Strings have indexes too
// Letter by letter
⏱ about 15 min

Monday: Strings have indexes too

Every hatch on Beacon Station has a tiny screen that shows a call sign. Rocket types "Nova 7" for the new drone bay. Then he wonders how much room it takes.

"Six," Raven says. Rocket counts again. "N, o, v, a, seven. That is five." Raven smiles. "What do you notice between the a and the seven?"

Nova peeks at the screen and giggles. "That is my name! Would you like a hint? A space is a character too. Python counts it."

Counting characters

A string is a row of characters. A character is one letter, digit, space or symbol.

len counts the characters in a string, just like it counts items in a list.

Each character has an index. The first index is 0, and -1 is the last one.

call = "Nova 7"
print(len(call))
print(call[0])
print(call[-1])
The screen shows
6
N
7
Index012345
CharacterNova(space)7
What does print(len("Bay 12")) show?
WHY THIS EXERCISESpaces count as characters. Forgetting them is a common mistake.
word = "ROCKET"
print(word[3])
print(word[-1])
First line on the screen
Second line on the screen
StatementTrue or false?
len("go now") is 6?
len("") is 0?
"Raven"[0] is "a"?
"Raven"[-1] is "n"?
WHY THIS EXERCISEThese are the building blocks for everything you will do with strings this week.
Try it
Write a short word on paper, one letter per box.
Number the boxes from 0. Circle index -1.

Practice lab: read the deck tag

tag = "Deck 9B"
print(len(tag))
print(tag[0])
print(tag[5])
print(tag[-1])
What does line 2 show?
What does line 4 show?
Which index holds the space?
ONE CHARACTER AT A TIME
  • Read the question.
  • Tap your answer.
What does line 3 show?
What does line 5 show?
What does len("") give?
StatementTrue or false?
len("Hi there") is 8?
"Kai"[1] is "a"?
"Kai"[3] is "i"?
A space is not a character.?
WHY THIS EXERCISEStrings follow the same index rules as lists, spaces and all.
What does print(len("Moon Base 4")) show?
WHY THIS EXERCISEThere are 9 letters and digits plus 2 spaces, so len gives 11.

Good counting! Tomorrow you will cut a string into pieces with a slice.