Find all the occurrences of a character in a string

Question:

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 By: theAlse

||

Answers:

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]
Answered By: avasal

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
Answered By: samfrances

text.find() only returns the first result, and then you need to set the new starting position based on that. So like this:

def findSectionOffsets(text):
    startingPos = 0

    position = text.find("|", startingPos):
    while position > -1:
        print position
        startingPos = position + 1
        position = text.find("|", startingPos)
Answered By: M Somerville

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.

Answered By: Marco L.

It is easier to use regular expressions here;

import re

def findSectionOffsets(text):
    for m in re.finditer('|', text):
        print m.start(0)
Answered By: Roland Smith
import re
def findSectionOffsets(text)
    for i,m in enumerate(re.finditer('|',text)) :
        print i, m.start(), m.end()
Answered By: Zulu

If text is the string that you want to count how many "|" it contains, the following line of code returns the count:

len(text.split("|"))-1

Note: This will also work for searching sub-strings.

Answered By: Pablo Reyes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.