查找字符串中的字符索引

时间:2016-03-26 21:01:05

标签: python regex string python-3.x

dave = [m.start() for m in re.finditer('*', "2345234*265354*26342567*356")]
print(dave)

每当我运行这段代码时,它就会给我带来这个巨大的错误。

Traceback (most recent call last):
File "C:\Users\Max\Desktop\MaxsCal V.1.py", line 107, in <module>
dave = [m.start() for m in re.finditer('*', "2345234*265354*26342567*356")]
File "C:\Program Files (x86)\Python 3\lib\re.py", line 220, in finditer
return _compile(pattern, flags).finditer(string)
File "C:\Program Files (x86)\Python 3\lib\re.py", line 293, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Program Files (x86)\Python 3\lib\sre_compile.py", line 536, in compile
p = sre_parse.parse(p, flags)
File "C:\Program Files (x86)\Python 3\lib\sre_parse.py", line 829, in parse
p = _parse_sub(source, pattern, 0)
File "C:\Program Files (x86)\Python 3\lib\sre_parse.py", line 437, in _parse_sub
itemsappend(_parse(source, state))
File "C:\Program Files (x86)\Python 3\lib\sre_parse.py", line 638, in _parse
source.tell() - here + len(this))
sre_constants.error: nothing to repeat at position 0

无论如何都要修改代码以提供输出,即*之类的所有[7, 14, 23]的索引。

3 个答案:

答案 0 :(得分:5)

re.finditer()使用正则表达式查找匹配项。在您的情况下,正则表达式为'*'*在正则表达式中具有特殊含义,因此如果您只想搜索一个星形字符,则需要将其转义:

dave = [m.start() for m in re.finditer('\\*', "2345234*265354*26342567*356")]

答案 1 :(得分:4)

您可以枚举索引:

>>> [index for index, value in enumerate("2345234*265354*26342567*356") if value == '*']
[7, 14, 23]

答案 2 :(得分:0)

您可以编写一个函数来查找所有字符的索引,如下所示:

def findChar(char, string):
    indexes = []
    b = 0
    for i in string:
        if i == char:
            indexes.append(b)
        b += 1
    return indexes

如果您真的想使用re,请查看poke的答案。