theAlse
theAlse

Reputation: 5757

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

Upvotes: 42

Views: 103570

Answers (7)

avasal
avasal

Reputation: 14872

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

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

also you can do

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

Upvotes: 20

M Somerville
M Somerville

Reputation: 4610

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)

Upvotes: 2

Pablo Reyes
Pablo Reyes

Reputation: 3123

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.

Upvotes: 2

Marco L.
Marco L.

Reputation: 1499

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.

Upvotes: 67

samfrances
samfrances

Reputation: 3705

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

Upvotes: 1

Zulu
Zulu

Reputation: 9285

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

Upvotes: 3

Roland Smith
Roland Smith

Reputation: 43533

It is easier to use regular expressions here;

import re

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

Upvotes: 2

Related Questions