I am trying to find all the occurences of \"|\" in a string.
def findSectionOffsets(text):
startingPos = 0
endPos = len(text)
for position in te
import re
def findSectionOffsets(text)
for i,m in enumerate(re.finditer('\|',text)) :
print i, m.start(), m.end()
if you want index of all occurance of |
character in a string you can do this
In [30]: import re
In [31]: str = "aaaaaa|bbbbbb|ccccc|ffffdd"
In [32]: [x.start() for x in re.finditer('\|', str)]
Out[32]: [6, 13, 19]
also you can do
In [33]: [x for x, v in enumerate(str) if v == '|']
Out[33]: [6, 13, 19]
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.
It is easier to use regular expressions here;
import re
def findSectionOffsets(text):
for m in re.finditer('\|', text):
print m.start(0)
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)
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