How to count the number of dashes between any two alphabetical characters?

Solution with regex:

import re

x = 'a--bc---d-k'

results = [
    len(m) for m in
    re.findall('(?<=[a-z])-*(?=[a-z])', x)
]
print(results)
print(''.join(str(r) for r in results))

output:

[2, 0, 3, 1]
2031

Solution with brute force loop logic:

x = 'a--bc---d-k'

count = 0
results = []
for c in x:
    if c == '-':
        count += 1
    else:
        results.append(count)
        count = 0
results = results[1:]  # cut off first length
print(results)

output:

[2, 0, 3, 1]

You can use a very simple solution like this:

import re

s = 'a--bc---d-k'
# Create a list of dash strings.
dashes = re.split('[a-z]', s)[1:-1]
# Measure the length of each dash string in the list and join as a string.
results = ''.join([str(len(i)) for i in dashes])

Output:

'2031'


If you input may also begin with a dash, you could use this:

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return all_counts

But if your input always starts with a letter, you may not like the 0 that's always at the head of the list.

If you need the output as a string of ints, then you could add this:

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return "".join([str(number) for number in all_counts])

Tags:

Python

String