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?
In Python, you can get the length of a string str (= number of characters) with the built-in function len() .
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.
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.
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])
'2031'
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With