Challenge - 5 Problems
String Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of negative step slicing
What is the output of this Python code?
text = 'abcdefg' result = text[5:2:-1] print(result)
Python
text = 'abcdefg' result = text[5:2:-1] print(result)
Attempts:
2 left
๐ก Hint
Remember that slicing with a negative step goes backwards and excludes the stop index.
โ Incorrect
The slice text[5:2:-1] starts at index 5 ('f'), goes backwards up to but not including index 2 ('c'), so it includes indices 5,4,3 which are 'f','e','d'.
โ Predict Output
intermediate2:00remaining
Slicing with omitted start and stop
What does this code print?
text = 'python' result = text[::-2] print(result)
Python
text = 'python' result = text[::-2] print(result)
Attempts:
2 left
๐ก Hint
When start and stop are omitted with a negative step, slicing goes from end to start.
โ Incorrect
text[::-2] means start from the end and take every second character backwards: indices 5('n'),3('h'),1('y').
โ Predict Output
advanced2:00remaining
Effect of out-of-range indices in slicing
What is the output of this code?
text = 'hello world' result = text[3:100] print(result)
Python
text = 'hello world' result = text[3:100] print(result)
Attempts:
2 left
๐ก Hint
Slicing does not raise errors if stop index is beyond string length.
โ Incorrect
Slicing stops at the string end if the stop index is too large. text[3:] is from index 3 to end: 'lo world'.
โ Predict Output
advanced2:00remaining
Slicing with step zero
What happens when you run this code?
text = 'example' result = text[::0] print(result)
Python
text = 'example' result = text[::0] print(result)
Attempts:
2 left
๐ก Hint
Step cannot be zero in slicing.
โ Incorrect
Using step=0 in slicing raises ValueError: slice step cannot be zero.
๐ง Conceptual
expert3:00remaining
Understanding slice indices with negative start and stop
Given the string
s = 'abcdefgh', what is the output of s[-3:-7:-1]?Python
s = 'abcdefgh' print(s[-3:-7:-1])
Attempts:
2 left
๐ก Hint
Negative indices count from the end. The slice goes backwards from -3 to -7 (excluded).
โ Incorrect
Index -3 is 'f' (index 5), -7 is 'b' (index 1). The slice goes backwards from index 5 down to 2 inclusive, so 'f','e','d','c'.