查找字符串中所有出现的字符

the*_*lse 27 python string

我试图找到"|"的所有出现 在一个字符串中.

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

    for position in text.find("|",startingPos, endPos):
        print position
        endPos = position
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:

    for position in text.find("|",startingPos, endPos):
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)

Mar*_* L. 43

功能:

def findOccurrences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]


findOccurrences(yourString, '|')
Run Code Online (Sandbox Code Playgroud)

将返回的索引列表yourString中的|出现.

  • 该函数在定义行上拼写错误.它应该是两个r的"def findOccurrences". (3认同)

ava*_*sal 12

如果你想要|字符串中所有字符出现的索引,你可以这样做

In [30]: import re

In [31]: str = "aaaaaa|bbbbbb|ccccc|dddd"

In [32]: [x.start() for x in re.finditer('\|', str)]
Out[32]: [6, 13, 19]
Run Code Online (Sandbox Code Playgroud)

你也可以

In [33]: [x for x, v in enumerate(str) if v == '|']
Out[33]: [6, 13, 19]
Run Code Online (Sandbox Code Playgroud)