Find all the occurrences of a character in a string

后端 未结 7 563
情深已故
情深已故 2020-12-01 12:02

I am trying to find all the occurences of \"|\" in a string.

def findSectionOffsets(text):
    startingPos = 0
    endPos = len(text)

    for position in te         


        
相关标签:
7条回答
  • 2020-12-01 12:28
    import re
    def findSectionOffsets(text)
        for i,m in enumerate(re.finditer('\|',text)) :
            print i, m.start(), m.end()
    
    0 讨论(0)
  • 2020-12-01 12:29

    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]
    
    0 讨论(0)
  • 2020-12-01 12:32

    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.

    0 讨论(0)
  • 2020-12-01 12:35

    It is easier to use regular expressions here;

    import re
    
    def findSectionOffsets(text):
        for m in re.finditer('\|', text):
            print m.start(0)
    
    0 讨论(0)
  • 2020-12-01 12:40

    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)
    
    0 讨论(0)
  • 2020-12-01 12:47

    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
    
    0 讨论(0)
提交回复
热议问题