Challenge - 5 Problems
String Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of positive and negative indexing
What is the output of this Python code?
Python
s = "hello" print(s[1], s[-1])
Attempts:
2 left
๐ก Hint
Remember, positive index starts at 0 from left, negative index starts at -1 from right.
โ Incorrect
s[1] is the second character 'e', s[-1] is the last character 'o'. So output is 'e o'.
โ Predict Output
intermediate2:00remaining
Indexing with negative values
What will this code print?
Python
word = "python" print(word[-3])
Attempts:
2 left
๐ก Hint
Count backwards from the end starting at -1.
โ Incorrect
word[-1] is 'n', word[-2] is 'o', word[-3] is 'h'.
โ Predict Output
advanced2:00remaining
Mixing positive and negative indexes
What is the output of this code snippet?
Python
text = "abcdef" print(text[2], text[-4])
Attempts:
2 left
๐ก Hint
Remember positive index 2 is third character, negative index -4 counts from right.
โ Incorrect
text[2] is 'c', text[-4] is 'c'. So output is 'c c'.
โ Predict Output
advanced2:00remaining
Index error with out-of-range negative index
What error does this code raise?
Python
s = "abc" print(s[-4])
Attempts:
2 left
๐ก Hint
Negative index must be within the string length.
โ Incorrect
Index -4 is out of range for string of length 3, so IndexError is raised.
๐ง Conceptual
expert2:00remaining
Length and indexing relationship
Given a string s of length 7, which index accesses the last character?
Attempts:
2 left
๐ก Hint
Positive indexes start at 0, so last index is length minus one.
โ Incorrect
For length 7, last character is at index 6 (0-based). s[7] is out of range. s[-7] is first character.