Skip to content
Advertisement

Count consecutive characters

How would I count consecutive characters in Python to see the number of times each unique digit repeats before the next unique digit?

At first, I thought I could do something like:

word = '1000'

counter = 0
print range(len(word))

for i in range(len(word) - 1):
    while word[i] == word[i + 1]:
        counter += 1
        print counter * "0"
    else:
        counter = 1
        print counter * "1"

So that in this manner I could see the number of times each unique digit repeats. But this, of course, falls out of range when i reaches the last value.

In the example above, I would want Python to tell me that 1 repeats 1, and that 0 repeats 3 times. The code above fails, however, because of my while statement.

How could I do this with just built-in functions?

Advertisement

Answer

A solution “that way”, with only basic statements:

word="100011010" #word = "1"
count=1
length=""
if len(word)>1:
    for i in range(1,len(word)):
       if word[i-1]==word[i]:
          count+=1
       else :
           length += word[i-1]+" repeats "+str(count)+", "
           count=1
    length += ("and "+word[i]+" repeats "+str(count))
else:
    i=0
    length += ("and "+word[i]+" repeats "+str(count))
print (length)

Output :

'1 repeats 1, 0 repeats 3, 1 repeats 2, 0 repeats 1, 1 repeats 1, and 0 repeats 1'
#'1 repeats 1'
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement