0
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?

4
  • 3
    How about using range(len(word) - 1)? Probably your error arises when j reaches the last character (i.e., j = len(word) - 1)) in which case j+1 is out of range. This might introduce (or not) another edge case when you provide an empty word. Deal with that separately if needed. Commented Nov 9, 2021 at 19:39
  • Why you post shows word[j:j+1] and the error word[j+1] Commented Nov 9, 2021 at 19:43
  • @azro I was trying to recreate the error… my bad Commented Nov 9, 2021 at 21:37
  • @j1-lee thanks a lot, that worked perfectly! Commented Nov 9, 2021 at 21:38

1 Answer 1

1

The thing is that the range generates from 0 (inclusive) to the string's length (exclusive) which is ok for indexing, as string are 0-based indexed, but you don't only access current index, also the next one, so when reaching the last value of j, the [j+1] is one too far

def double_chars(word):
    chars_count = 0
    for j in range(len(word) - 1):
        if word[j] == word[j + 1]:
            chars_count += 1
    return chars_count
0 1 2 3 4 5 6 7 8 9 10 11
x[j] H e l l o . . w o r l d
x[j+1] e l l o . . w o r l d !

One-liner proposal, and another with zip

def double_chars(word):
    return sum(1 for j in range(len(word) - 1) if word[j] == word[j + 1])

def double_chars(word):
    return sum(1 for ch_curr, ch_next in zip(word, word[1:]) if ch_curr == ch_next)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the response! Your answer solves the problem and also helps me understand better. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.