1. Indexing
A string is text between quotes, like "Python". Each character has an index: a position counted from 0.
You read a single character with subscript syntax:
text— any string: for example"Python", or a variable that holds a string.index— an integer (a whole number).0is the first character,1the second, and so on.- The result is a new string containing exactly one character.
A negative index counts from the end of the string: -1 is the last character, -2 the one before it.
Indexing works the same on a variable:
Only positions that exist are valid. "Python" has six characters, so its valid indexes are 0 to 5 and -1 to -6. Any other index raises an IndexError, an error that says the index is out of range, and the program stops:
Read index 0
Index 0 is the first character of a string. Print the character at index 0 of "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a positive index
Index 1 is the second character, index 2 the third, and so on. Print the character at index 3 of "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Count from the end
A negative index counts from the end: -1 is the last character and -2 is the one before it. Print the character at index -2 of "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Both ends
Index 0 is the first character and index -1 is the last one. Print the first character of "Python", then its last character.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Index a variable
Indexing works the same on a variable that holds a string. Create a variable named word with the value "Python", then print the character at index 1 using word.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Trigger an IndexError
"Python" has 6 characters, so its valid indexes are 0 to 5 (and -1 to -6). Index 6 is out of range: reading it raises IndexError and the program stops.
Create a variable named word with the value "Python" and print word[6]. Running it must stop with:
Create a free account to save your progress and unlock chapter 2.