How do you find all occurrences of a character in a string in python?

I am trying to find all the occurences of "|" in a string.

def findSectionOffsets[text]:
    startingPos = 0
    endPos = len[text]

    for position in text.find["|",startingPos, endPos]:
        print position
        endPos = position

But I get an error:

    for position in text.find["|",startingPos, endPos]:
TypeError: 'int' object is not iterable

asked Oct 22, 2012 at 10:39

2

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.

Mooncrater

3,5444 gold badges26 silver badges53 bronze badges

answered Oct 22, 2012 at 10:50

Marco L.Marco L.

1,4794 gold badges17 silver badges25 bronze badges

3

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] # 

Chủ Đề