def double_chars(word):
for j in range(len(word)):
if word[j] == word[j:j+1]:
chars_count = chars_count + 1
return chars_count
test_word = "Hello..world!"
print(double_chars(test_word))
Error: if word[j] == word[j+1]:
IndexError: string index out of range
I keep getting string index out of range on this function. I have tried different ways of indexing and slicing.
I am trying to return the count of character in a string that has double characters for example: bell--rung --> "ll" = 1, and "--" = 1. hence count of 2.
Am I doing something wrong in the code?
range(len(word) - 1)? Probably your error arises whenjreaches the last character (i.e.,j = len(word) - 1)) in which casej+1is out of range. This might introduce (or not) another edge case when you provide an emptyword. Deal with that separately if needed.word[j:j+1]and the errorword[j+1]