Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the occurrences of a character in a string

Tags:

python

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 
like image 254
theAlse Avatar asked Oct 22 '12 10:10

theAlse


People also ask

How do you find the occurrences of a character in a string in Python?

Python String count() The count() method returns the number of occurrences of a substring in the given string.

Which method finds the list of all occurrences of the pattern in the given string in Python?

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.

Which method finds the list of all occurrences?

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.


2 Answers

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.

like image 147
Marco L. Avatar answered Sep 20 '22 01:09

Marco L.


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] 
like image 35
avasal Avatar answered Sep 19 '22 01:09

avasal