Python
character position
string indexing
coding tutorial
Python programming

How to get the position of a character in Python?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In Python, getting the position of a character usually means finding its index inside a string. The right method depends on what you want when the character is missing and whether you need only the first match or every match. Python gives you both forgiving and strict options, so it is worth choosing the one that matches your error-handling style.

Use find for a Safe First Match

The simplest method is str.find. It returns the lowest index of the match or -1 if the character is not present.

python
1text = "banana"
2position = text.find("a")
3
4print(position)

This prints 1 because the first "a" is at index 1.

If the character is not present:

python
1text = "banana"
2position = text.find("z")
3
4print(position)

This prints -1. That makes find a good choice when "not found" is expected and should not raise an exception.

Use index When Missing Data Should Be an Error

If a missing character means the input is invalid, str.index is often better because it raises ValueError instead of silently returning -1.

python
1text = "banana"
2position = text.index("n")
3
4print(position)

This prints 2. But if the character is missing:

python
text = "banana"
position = text.index("z")

Python raises an exception. That behavior is useful when the caller should not continue with missing input.

Find the Last Match with rfind or rindex

If you need the last occurrence instead of the first, use the reverse versions.

python
1text = "banana"
2
3print(text.rfind("a"))
4print(text.rindex("a"))

Both return 5 here because the last "a" is at index 5. The difference is the same as before:

  • 'rfind returns -1 when missing'
  • 'rindex raises ValueError'

These methods are usually better than reversing the string manually.

Get Every Position with enumerate

If the character may appear several times and you need all positions, loop with enumerate.

python
1text = "banana"
2positions = [index for index, char in enumerate(text) if char == "a"]
3
4print(positions)

This prints [1, 3, 5].

This pattern is readable and works for any condition, not just one exact character. For example, you could find the positions of every vowel or every digit using the same structure.

Search for Substrings Too

The same string methods work for substrings, not only one character.

python
text = "abracadabra"
print(text.find("cad"))

This returns 4. The index always refers to the start of the match.

If you need all substring occurrences, a loop is usually clearer than trying to stretch one method too far:

python
1text = "abracadabra"
2needle = "abra"
3positions = []
4start = 0
5
6while True:
7    pos = text.find(needle, start)
8    if pos == -1:
9        break
10    positions.append(pos)
11    start = pos + 1
12
13print(positions)

This finds overlapping or repeated occurrences in a controlled way.

Understand What the Index Means

Python string indexes are zero-based. That means:

  • the first character is at index 0
  • the second character is at index 1
  • and so on

This matters when converting the result into something user-facing. If a UI or report expects positions starting from 1, add 1 explicitly instead of assuming Python already uses that convention.

Unicode Usually Works Naturally

For ordinary Python text operations, these methods work with Unicode strings too.

python
text = "café"
print(text.find("é"))

This behaves as expected in normal cases. The main caution is that some visually similar Unicode sequences can be represented in more than one way, so normalization matters if text came from mixed sources.

Common Pitfalls

  • Using index when missing values are normal and then getting avoidable ValueError exceptions.
  • Forgetting that Python indexes start at 0.
  • Using find and forgetting to check for -1 before using the result.
  • Writing complicated loops for last-match searches when rfind or rindex already exists.
  • Assuming substring search works differently from character search when the same core methods already handle both.

Summary

  • Use find when you want the first position and a safe -1 when the character is missing.
  • Use index when a missing character should raise an error.
  • Use rfind or rindex for the last occurrence.
  • Use enumerate when you need every matching position.
  • Remember that Python string indexes are zero-based and apply to substrings as well as single characters.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.