Find all the occurrences of a character in a string

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

It is easier to use regular expressions here;

import re

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

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.


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]

Tags:

Python

String