Nearby lessons

57 of 108

Python - String Indexing

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.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
p
y
t

Negative Indexing

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
n
o
h

Accessing First and Last Characters

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
First Character: d
Last Character: a

Using Variables as Index

We can use variables as index values.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
h

Index Out of Range

If index exceeds string range, IndexError occurs.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
IndexError: string index out of range

Iterating String Using Index

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

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
python

Reverse Order Traversal

We can access characters in reverse order using negative indexing.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
nohtyp

Difference Between Positive and Negative Indexing

Positive Indexing Negative Indexing
Left to rightRight to left
Starts from 0Starts from -1
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
p
p

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.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Enter Some String:durga
The character present at positive index 0 and at negative index -5 is d
The character present at positive index 1 and at negative index -4 is u
The character present at positive index 2 and at negative index -3 is r
The character present at positive index 3 and at negative index -2 is g
The character present at positive index 4 and at negative index -1 is a

Sample Output:

Important Points

  • String indexing starts from 0 in the forward direction.
  • Negative indexing starts from -1 in the backward direction.
  • Every character in a string has both a positive index and a negative index.
  • Invalid indexes raise an IndexError.

Summary

Feature Description
Positive IndexLeft to right
Negative IndexRight to left
First Positive Index0
First Negative Index-1
Error for Invalid IndexIndexError

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Python - String Slicing