Strings – Slicing

Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.

Strings – Slicing

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

1. What does 'Python'[0:3] return?
A 'Pyth'
B 'Pyt'
2. What does 'hello'[:2] return?
A 'he'
B 'hel'
3. What does 'hello'[3:] return?
A 'llo'
B 'lo'
4. Is the stop index included in a slice?
A No it stops before it
B Yes
5. What does 'abcdef'[::2] return?
A 'ace'
B 'bdf'

Match the Pairs

Draw a line connecting each item on the left to its match on the right.

Left columnRight column
1'hello'[1,4] AOk: Reverses the string
2'hello'[10:20] BValid: Returns 'hel'
3'hello'[:3] CError: Use colon not comma
4'hello'[::-1] DInvalid: But returns '' not error
5print('hello'[1:4]) EOutput: ell
6print('python'[2:]) FOutput: thon

Definitions

Slice

Fill in the Blanks

Complete each line of code by filling in the missing parts.

1.
word = 'Python' print(word[_:3])
2.
word = 'hello' print(word[:_])
3.
word = 'hello' print(word[_:])
4.
word = 'hello' print(word[::__])
5.
text = 'abcdef' print(text[1:_])

Spot the Error

Shade in the letter of the line that contains an error.

Question 1
A word = 'hello'
B part = word[0,3]
C print('Slice:', part)
D print('Done')
Question 2
A word = 'hello'
B part = word[1:4:0]
C print('Slice:', part)
D print('Done')
Question 3
A word = 'hello'
B part = word(1:3)
C print('Slice:', part)
D print('Done')
Question 4
A word = 'hello'
B part = word[0:5:]
C print('Slice:', part)
D # trying to get all
Question 5
A part = 'hello'[-1:-4]
B word = 'hello'
C print('Slice:', part)
D print('Done')

Answer Key

Strings – Slicing
Section A: Quick Questions
Q1
B — 'Pyt'
Q2
A — 'he'
Q3
B — 'lo'
Q4
A — No it stops before it
Q5
A — 'ace'
Section B: Match the Pairs
Q1
'hello'[1,4] → Error: Use colon not comma
Q2
'hello'[10:20] → Invalid: But returns '' not error
Q3
'hello'[:3] → Valid: Returns 'hel'
Q4
'hello'[::-1] → Ok: Reverses the string
Q5
print('hello'[1:4]) → Output: ell
Q6
print('python'[2:]) → Output: thon
Section C: Definitions
Q1
Slice — Extract a portion of a string using [start:stop].~~[start:stop]
Section D: Fill in the Blanks
Q1
word = 'Python' print(word[0:3])
Q2
word = 'hello' print(word[:3])
Q3
word = 'hello' print(word[2:])
Q4
word = 'hello' print(word[::-1])
Q5
text = 'abcdef' print(text[1:5])
Section E: Spot the Error
Q1
B — Use colon : for slicing, not comma
Q2
B — Step cannot be 0: causes ValueError
Q3
B — Use square brackets [] for slicing, not parentheses ()
Q4
B — Trailing colon without step is fine but unnecessary: remove it for clarity
Q5
A — Start must be before stop: -4 comes before -1 in the string