☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

Strings in Python

الأسبوع 6 · الدرس ٣ «السلاسل النصية والقوائم في لغة Python» (١): السلاسل النصية والطول والفهرس والحلقة والبحث · 3 دروس
2

Index: counting from zero, and from the end

ICT Prep 3 Term 1, Unit 1, Lesson 3: pp. 32–34
GoalFind a character by its index, counting from zero and from the end, and recognise an IndexError.
New words
index · the position number of a character in a stringnegative index · a position counted back from the end: -1 is the last characterIndexError · the error shown when an index is outside the stringsquare brackets · [ ] after the name, holding the index
Explanation

Every character of a string has a position number called an index, and Python starts counting at zero. For text = "school", the first character text[0] is s, text[3] is o and the last, text[5], is l. Python also counts backwards from the end with negative numbers: text[-1] is the last character l, and text[-6] is the first, s. So negative numbering starts at -1 for the last character, it does not start at zero. The sheet shows both rows of numbers under the letters. If you ask for a position that does not exist, such as text[6] for a string of length 6, Python stops with an IndexError, which means the index is out of range. The last valid index is always the length minus one.

ABCDEF
1school
2012345
3−6−5−4−3−2−1
Worked examples
Python
1text = "school"
2print(text[0])
3print(text[3])
4print(text[-1])
5print(text[-6])
Output
s
o
l
s
Salma asks for four characters of school. The numbers in brackets decide which character is shown.
Python
1text = "school"
2print(text[6])
Output
IndexError: the index is out of range
The string school has length 6, so the valid indexes are 0 to 5. Asking for text[6] is out of range. Python stops and shows an IndexError.
Class activity

Take the string "garden". Draw the sheet with the letters, the numbers from 0 and the numbers from -6. Which letter is text[2]? Which letter is text[-2]? Which index would cause an IndexError?

Practice
1
In "school", which character is text[0]?
2
Which index gives the last character of any string?
3
A string has length 10. What is its last valid positive index?
4
What error appears for text[6] when text = "school"?