2017-08-13 34 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