Count consecutive characters

后端 未结 9 1575
别那么骄傲
别那么骄傲 2020-11-28 06:44

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

9条回答
  •  抹茶落季
    2020-11-28 07:34

    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'
    

提交回复
热议问题