Python strings – Get all positions of a character within a string

In this post we will be creating a Python script that will return all positions of a character within a string. To do this we will use enumeration which will enable us to a counter as it iterates over the string.

The string we will use for this example is ‘hello how are you’. We will be retrieving all positions of the letter ‘o’, see the snippet of code below for how this is done.

string = 'hello how are you'
letter = 'o'
print([pos for pos, char in enumerate(string) if char == letter])

The above would return the following as output.

[4, 7, 15]

Leave a Reply