Back to Chapters
Chapter Progress: 0 %0 / 4 Lessons Read
‹›

3. Strings

3.1 Indexing

Highlights & notes

Select lesson text to highlight it, or tap Add note.

    Bookmarks

    Bookmark a lesson to see it here.

      🧒 The easy way

      A string is a train of letters. Each coach has a seat number, and the first seat is 0, not 1.

      • word[0] is the first letter.
      • word[-1] is the last letter.
      • Counting starts at 0, like floors in a lift.

      Thumb rule: First is [0]. Last is [-1].

      Watch it run · 1

      Python
      print("PYTHON"[0])
      Result
      P

      Watch it run · 2

      Python
      print("PYTHON"[-1])
      Result
      N

      A string is a row of characters, and each character has a position called an index. Like lists, counting starts at 0.

      • code = "B704"
      • code[0] → "B" (first)
      • code[3] → "4"
      • code[-1] → "4" (last)
      • code[-2] → "0"

      Asking for a position that doesn’t exist, such as code[10], raises IndexError: string index out of range.

      For code = "B704":

      • B → index 0 or -4
      • 7 → index 1 or -3
      • 0 → index 2 or -2
      • 4 → index 3 or -1
      Must Know:

      Strings can’t be changed in place. code[0] = "C" raises TypeError. Build a new string instead: "C" + code[1:].

      How it fits together

      1. "B704"
      2. code[0] → B
      3. code[-1] → 4

      Step through the code

      Python

      batch_code = "B704"print(batch_code[0])print(batch_code[-1])

      Output

      B
      4

      Practice in Python

      Print the first and last characters of source on one line.

      Expected output
      o s

      Reference solution
      source = "orders"
      print(source[0], source[-1])

      Question 1 · Easy

      name = "Python". What is name[0]?

      Question 2 · Medium

      name = "Python". What is name[-2]?

      Question 3 · Hard

      city = "Noida". What does city[5] give?

      Key takeaways

      Indexes start at zero and negative indexes count from the end.

      Lesson 10 of 67

      Save your progress

      Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.

      Start free Log in
      PreviousIndexing
      Save your progress free for 1 month. Start free · Log in