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?
CodePudding user response:
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)