Find all the occurrences of a character in a string

Solution 1:

The function:

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


findOccurrences(yourString, '|')

will return a list of the indices of yourString in which the | occur.

Solution 2:

if you want index of all occurrences of | character in a string you can do this

import re
str = "aaaaaa|bbbbbb|ccccc|dddd"
indexes = [x.start() for x in re.finditer('\|', str)]
print(indexes) # <-- [6, 13, 19]

also you can do

indexes = [x for x, v in enumerate(str) if v == '|']
print(indexes) # <-- [6, 13, 19]

Solution 3:

It is easier to use regular expressions here;

import re

def findSectionOffsets(text):
    for m in re.finditer('\|', text):
        print m.start(0)

Solution 4:

import re
def findSectionOffsets(text)
    for i,m in enumerate(re.finditer('\|',text)) :
        print i, m.start(), m.end()

Solution 5:

text.find returns an integer (the index at which the desired string is found), so you can run for loop over it.

I suggest:

def findSectionOffsets(text):
    indexes = []
    startposition = 0

    while True:
        i = text.find("|", startposition)
        if i == -1: break
        indexes.append(i)
        startposition = i + 1

    return indexes