Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

If we have a string of alphabetical characters and some dashes, and we want to count the number of dashes between any two alphabetic characters in this string. what is the easiest way to do this?

Example:

Input: a--bc---d-k

output: 2031

This means that there are 2 dashes between a and b, 0 dash between b and c, 3 dashes between c and d and 1 dash between d and k

what is a good way to find this output list in python?

like image 893
b.j Avatar asked Mar 18 '20 13:03

b.j


People also ask

How do you count characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .

How do you count letters and numbers in Python?

First we find all the digits in string with the help of re. findall() which give list of matched pattern with the help of len we calculate the length of list and similarly we find the total letters in string with the help of re. findall() method and calculate the length of list using len.

How do you count the number of times a letter appears in a string in Python?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string. Remember, upper and lower cases are treated as different characters.


2 Answers

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'

like image 117
S3DEV Avatar answered Oct 01 '22 00:10

S3DEV


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]
like image 41
Boseong Choi Avatar answered Oct 01 '22 02:10

Boseong Choi