尝试计算出现重叠的字符串时出现索引错误

时间:2018-09-21 16:26:06

标签: python string python-3.x indexing

我正在尝试在=SUM(ISNUMBER(MATCH($A9:$A11,{"Wheat","Rye"},0))*(C9:C11>0)*($B9:$B11<MMULT($C9:C11,TRANSPOSE(COLUMN($C9:C11)^0)))) 中查找var names = ['Home', 'About', 'Contact']; <Router> <div> <ul> {names.map(function(name, index){ return <li key={ index }><Link to="/">{name}</Link></li>; })} </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/contact" component={Contact}/> </div> </Router> 的计数。我在第10行收到“索引超出范围”错误,而且我无法弄清楚。 bob应该为3。

ls

3 个答案:

答案 0 :(得分:0)

尝试通过检查索引来坚持尝试的方法,您可以执行以下操作:

s = 'azcbobobegghakl'
bob_count = 0 
for idx, item in enumerate(s[:-2]):
    if s[idx: idx+3] == 'bob':
        bob_count += 1

print(bob_count)
(xenial)vash@localhost:~/python/stack_overflow/sept$ python3.7 bob.py
2

如果您要向前看,请index +1,最后的索引将不起作用,您必须注意索引的内容以及对该索引的操作。

答案 1 :(得分:0)

python中str的count()函数。

In [31]: s ='azcbobobegghbobfdfdbob'

In [32]: print(s.count('bob'))
3

要查找首次出现的索引,可以使用index()函数

In [34]: print(s.index('bob'))
3

要找到所有出现的索引,可以使用python的re模块

import re
In [44]: for val in re.finditer('bob', s):
    ...:     print(val.span()[0])
    ...:
3
12
19

答案 2 :(得分:0)

我只解释错误发生的位置和原因。

s = 'azcbobobegghakl'
ls =[]
for x in s:
    ls.append(x)
    print(ls)
#equal to
#ls = list(s)

for z in ls:
    count = 0
    i = ls.index("b")
    print(z) # !!!! z just a single letter,you can not use index on it !!!
    if z[i] == "b":
        if z[i+1] == "o":
            if z[i+2] == "b":
                count +=1

按照你的想法,我想你要这样写:

但这是不正确的,因为i = ls.index("b")永远不变,因此您匹配了相同的单词15 times

s = 'azcbobobegghakl'
ls =[]

for x in s:
    ls.append(x)
    print(ls)

ls = list(s)
for z in ls:
    count = 0
    i = ls.index("b")
    print(z) # z just a single letter,you can not use index on it
    if ls[i] == "b": #but ls can do this
        if ls[i+1] == "o":
            if ls[i+2] == "b":
                count +=1
print(count)

要简短

import re
s = 'azcbobobegghakl'
print(len(re.findall("b(?=ob)",s)))
相关问题