gpt4 book ai didi

python - 查找字符串中字符的索引

转载 作者:行者123 更新时间:2023-11-28 20:04:35 26 4
gpt4 key购买 nike

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].

最佳答案

re.finditer()使用正则表达式查找匹配项。在您的情况下,该正则表达式是 '*'*在正则表达式中有特殊含义,所以如果你只是想搜索一个星号,你需要将它转义:

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

关于python - 查找字符串中字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com