0
0
Pythonprogramming~20 mins

String indexing (positive and negative) in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
String Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of positive and negative indexing
What is the output of this Python code?
Python
s = "hello"
print(s[1], s[-1])
Ah o
Be o
Ce h
Do e
Attempts:
2 left
๐Ÿ’ก Hint
Remember, positive index starts at 0 from left, negative index starts at -1 from right.
โ“ Predict Output
intermediate
2:00remaining
Indexing with negative values
What will this code print?
Python
word = "python"
print(word[-3])
Ah
Bt
Co
Dn
Attempts:
2 left
๐Ÿ’ก Hint
Count backwards from the end starting at -1.
โ“ Predict Output
advanced
2:00remaining
Mixing positive and negative indexes
What is the output of this code snippet?
Python
text = "abcdef"
print(text[2], text[-4])
Ac d
Bd d
Cd c
Dc c
Attempts:
2 left
๐Ÿ’ก Hint
Remember positive index 2 is third character, negative index -4 counts from right.
โ“ Predict Output
advanced
2:00remaining
Index error with out-of-range negative index
What error does this code raise?
Python
s = "abc"
print(s[-4])
AIndexError
BNo error, prints 'a'
CTypeError
DKeyError
Attempts:
2 left
๐Ÿ’ก Hint
Negative index must be within the string length.
๐Ÿง  Conceptual
expert
2:00remaining
Length and indexing relationship
Given a string s of length 7, which index accesses the last character?
As[7]
Bs[-6]
Cs[6]
Ds[-7]
Attempts:
2 left
๐Ÿ’ก Hint
Positive indexes start at 0, so last index is length minus one.