Nearby lessons

62 of 159

Python - String Indexing

📌 What You Will Learn
  • Understand what string indexing is and how it accesses individual characters
  • Use zero-based positive indexing that starts at 0
  • Use negative indexing that starts at -1
  • Iterate a string using a for loop and range(len(s))
  • Handle IndexError for out-of-range indexes
  • Apply indexing in character extraction and password validation

What Is String Indexing?

String indexing is used to access individual characters from a string. Python supports both positive and negative indexing.

Zero-Based Indexing

Python follows zero-based indexing, so the first character starts from 0.

Character Positive Index Negative Index
d0-5
u1-4
r2-3
g3-2
a4-1

Positive Indexing

Positive indexing starts from 0 and moves left to right.

Loading editor…

Negative Indexing

Negative indexing starts from -1 and moves right to left.

Loading editor…

Accessing First and Last Characters

Loading editor…

Using Variables as Index

We can use variables as index values.

Loading editor…

Index Out of Range

If index exceeds string range, IndexError occurs.

Loading editor…

Iterating String Using Index

We can access characters one by one using a loop and indexing.

Loading editor…

Reverse Order Traversal

We can access characters in reverse order using negative indexing.

Loading editor…

Difference Between Positive and Negative Indexing

Positive Indexing Negative Indexing
Left to rightRight to left
Starts from 0Starts from -1
Loading editor…

Real World Usage

String indexing is useful for character extraction, password validation, data processing, parsing text, and pattern matching.

Program to Display Characters with Positive and Negative Index

This program prints each character along with its positive and negative index, matching the Word file example.

Loading editor…
📝 Key Takeaways
  • String indexing accesses individual characters with square brackets
  • Positive indexes start at 0 and move left to right
  • Negative indexes start at -1 and move right to left
  • An index outside the string range raises IndexError
  • Indexing can be combined with loops and variables for traversal

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.