Group by a single character otherwise split

Viewed 81

I have the following string:

"TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"

I would like to be able to group by the T's into a list and then count the number of T's to the first H.

i.e. so like

[3, 1, 2, 4, 3, 6, 5, 1]

Whats the most efficient way to do this in python ?

4 Answers

Another approach using list comprehension :

my_string = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"

strips = my_string.strip('H')
splits = strips.split('H' )

# generating iterables of 1 and then summation 
my_list = [sum(1 for i in j) for j in splits]

print(my_list )

gives

[3, 1, 2, 4, 3, 6, 5, 1]

[Program finished]
Related