theAlse theAlse - 1 month ago 19
Python Question

Find all the occurrences of a character in a string

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

Answer

The function

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


findOccurrences(yourString, "|")

will return a list of the indexes of yourString in which the | occur

Comments