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
Python String count() The count() method returns the number of occurrences of a substring in the given string.
The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them.
Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match. start() and match.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With