0
0
Pythonprogramming~20 mins

String slicing behavior in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
String Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A'cde'
B'def'
C'fed'
D'edc'
Attempts:
2 left
๐Ÿ’ก Hint
Remember that slicing with a negative step goes backwards and excludes the stop index.
โ“ Predict Output
intermediate
2: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)
A'nhy'
B'nohty'
C'nhot'
D'nht'
Attempts:
2 left
๐Ÿ’ก Hint
When start and stop are omitted with a negative step, slicing goes from end to start.
โ“ Predict Output
advanced
2: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)
A'lo world!'
B'lo world'
CIndexError
D'lo worl'
Attempts:
2 left
๐Ÿ’ก Hint
Slicing does not raise errors if stop index is beyond string length.
โ“ Predict Output
advanced
2: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)
AValueError
B'' (empty string)
C'example'
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Step cannot be zero in slicing.
๐Ÿง  Conceptual
expert
3: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])
A'defg'
B'efgh'
C'dcba'
D'fedc'
Attempts:
2 left
๐Ÿ’ก Hint
Negative indices count from the end. The slice goes backwards from -3 to -7 (excluded).