Skip to content

Python find all indexes of character in a string | Example code

  • by

You don’t need to use a special method to find all indexes of characters in a string in Python. Just use for-loop and if statement logic to get done this task.

Python find all indexes of character in a string Example

Simple example code finds all occurrence index of “s” char in a given string.

text = 'Python is easy programing language'

s = 's'
res = []
for i in range(len(text)):
    if text[i] == s:
        res.append(i)

print(res)

Output:

Python find all indexes of character in a string

How to find char in string and get all the indexes?

Here is another approach using enumerate to get a list of all indexes of char.

text = 'Python is easy programing language'


def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]


print(find(text, 's'))

Output: [8, 12]

Do comment if you have any doubts and suggestions on this Python char index topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading