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

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.