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.
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
print("PYTHON"[0])P
Watch it run · 2
print("PYTHON"[-1])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→ index0or-47→ index1or-30→ index2or-24→ index3or-1
Strings can’t be changed in place. code[0] = "C" raises TypeError. Build a new string instead: "C" + code[1:].
How it fits together
- "B704"
- code[0] → B
- 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 ✓ Solved
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.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in