Python | Count K character between consecutive characters

Sometimes, while working with strings, we can have a problem in which we need to check the count of each character between the consecutive character. This type of problem can have application in day-day and web development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate the list counting the K character between each of characters.
Python3
# Python3 code to demonstrate working of # Count K character between consecutive characters# Using loop# initializing stringtest_str = "g...f..g.i..s....b..e....s...t"# printing original stringprint("The original string is : " + test_str)# initializing K K = '.'# Count K character between consecutive characters# Using loopcount = 0res = []for ele in test_str: if ele == K: count += 1 else: res.append(count) count = 0res = res[1:]# printing result print("List of character count : " + str(res)) |
The original string is : g...f..g.i..s....b..e....s...t List of character count : [3, 2, 1, 2, 4, 2, 4, 3]
Method #2 : Using list comprehension + findall() This is yet another way in which this problem can be solved. In this, we check for occurring K character using findall() and list comprehension is used to iterate about the string.
Python3
# Python3 code to demonstrate working of # Count K character between consecutive characters# Using list comprehension + findall()import re# initializing stringtest_str = "g---f--g-i--s----b--e----s---t"# printing original stringprint("The original string is : " + test_str)# Count K character between consecutive characters# Using list comprehension + findall()res = [len(ele) for ele in re.findall('(?<=[a-z])-*(?=[a-z])', test_str)]# printing result print("List of character count : " + str(res)) |
The original string is : g---f--g-i--s----b--e----s---t List of character count : [3, 2, 1, 2, 4, 2, 4, 3]
Method #3 : Using replace(),split(),count() methods
Approach
- Replace all characters except K in a string by *
- Split string by * which results in a list
- For each string check count of K and append count to output list
- Display output list
Python3
# Python3 code to demonstrate working of# Count K character between consecutive characters# Using loop# initializing stringtest_str = "g---f--g-i--s----b--e----s---"# printing original stringprint("The original string is : " + test_str)# initializing KK = '-'# Count K character between consecutive characters# Using loopfor i in test_str: if i!=K: test_str=test_str.replace(i,"*")x=test_str.split("*")res=[]for i in x: if(i.count(K)!=0): res.append(i.count(K))# printing resultprint("List of character count : " + str(res)) |
The original string is : g---f--g-i--s----b--e----s--- List of character count : [3, 2, 1, 2, 4, 2, 4, 3]
Time Complexity : O(N) N – length of splitted list
Auxiliary Space : O(N) N – length of output list



