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
test_str = "g...f..g.i..s....b..e....s...t"
print ("The original string is : " + test_str)
K = '.'
count = 0
res = []
for ele in test_str:
if ele = = K:
count + = 1
else :
res.append(count)
count = 0
res = res[ 1 :]
print (" List of character count : " + str (res))
|
Output :
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
import re
test_str = "g - - - f - - g - i - - s - - - - b - - e - - - - s - - - t"
print ("The original string is : " + test_str)
res = [ len (ele) for ele in re.findall( '(?<=[a-z])-*(?=[a-z])' , test_str)]
print (" List of character count : " + str (res))
|
Output :
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
test_str = "g---f--g-i--s----b--e----s---"
print ( "The original string is : " + test_str)
K = '-'
for 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))
print ( "List of character count : " + str (res))
|
Output
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
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...