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

Tuesday

Slice a string
// Letter by letter
⏱ about 15 min

Tuesday: Slice a string

The launch board shows codes like GATE4-0900. The gate is at the front, and the time is at the back. Rocket needs to pull out just the time for the schedule.

"I will copy it letter by letter," he says. Raven shakes her head. "What do you notice? The time is always in the same spots."

Nova draws two glowing brackets around the last four digits. "Would you like a hint? Python can cut out a piece of a string. Just say where to start and stop."

A slice takes a piece

A slice cuts a piece out of a string. Write the start index, a colon, then the stop index.

The slice includes the start. It stops just before the stop index.

word = "ROCKET"
print(word[0:3])
print(word[3:6])
print(word[1:4])
The screen shows
ROC
KET
OCK
Index012345
CharacterROCKET
  • word[0:3] takes index 0, 1 and 2. It stops before 3.
  • Stop minus start tells you how many characters you get: 3 minus 0 is 3.
  • If you leave out the start, Python starts at 0. word[:3] is the same as word[0:3].
place = "STATION"
print(place[0:4])
print(place[4:7])
First line on the screen
Second line on the screen
code = "GATE4-0900"
print(code[6:10])
What does the program above show?
WHY THIS EXERCISEReal data often hides useful pieces in fixed spots. A slice gets them out.
PICK THE SLICE
  • Read the question.
  • Tap your answer.
Which slice gives "MOON" from "MOONBASE"?
Try it
Write SPACESHIP on paper with an index under each letter.
Find the slice that gives SHIP.
ship = "COMETRUN"
print(ship[0:5])
print(ship[5:8])
print(ship[2:6])
What does line 2 show?
What does line 3 show?
What does line 4 show?
SLICE CHECK
  • Read the question.
  • Tap your answer.
How many characters does word[2:7] give?
word[:3] is the same as which slice?
Which slice gives "BASE" from "MOONBASE"?
StatementTrue or false?
"PLANET"[0:3] is "PLA"?
"PLANET"[3:6] is "NET"?
"PLANET"[1:3] is "PLA"?
A slice includes its stop index.?
WHY THIS EXERCISEA slice stops just before the stop index. That rule is easy to forget.
What does print("LAUNCHPAD"[6:9]) show?
WHY THIS EXERCISEIndex 6, 7 and 8 spell PAD. The slice stops before 9.

Sharp slicing! Tomorrow you will make strings shout and whisper with upper and lower.

← Monday