2017-08-13 68 views
-3

我想比较字符串中的下列字符,如果它们相等,请提高计数器。 用我的示例代码,我总是得到与第6行相关的TypErrors。 你知道问题出在哪里吗?在Python中比较字符串中的字符

谢谢!

def func(text): 
    counter = 0 
    text_l = text.lower() 

    for i in text_l: 
     if text_l[i+1] == text_l[i]: 
      print(text_l[i+1], text_l[i]) 
      counter += 1 

    return counter 
+0

'对于text_l中的i:'迭代_individual个字符_,以便在每次迭代时输入(i)== str'。 – ForceBru

回答

2

i的索引。您的for将直接迭代元素,因此i在任何时间点都是字符,而不是整数

for i in range(len(text_l) - 1): # i is the current index 
    if text_l[i + 1] == text_l[i]: 

您还可以使用enumerate:如果你想索引使用range功能

for i, c in enumerate(text_l[:-1]): # i is the current index, c is the current char 
    if text_l[i + 1] == c: 

在这两种情况下,你要迭代,直到倒数第二个字符,因为,你会打IndexErrori + 1最后一次迭代i + 1超出了最后一个字符的范围。

+0

这段代码中有一个错误,因为'i + 1'将跳出界限。 – ForceBru

+0

@ForceBru谢谢!固定。 –

+0

哈哈,那么容易。谢谢! – user3714215