如何计算任意两个字母字符之间的破折号数?

b.j*_*b.j 9 python string

如果我们有一串字母字符和一些破折号,我们想计算这个字符串中任意两个字母字符之间破折号的数量。最简单的方法是什么?

例子:

输入: a--bc---d-k

输出: 2031

这意味着a和b之间有2个破折号,b和c之间有0个破折号,c和d之间有3个破折号,d和k之间有1个破折号

在 python 中找到这个输出列表的好方法是什么?

S3D*_*DEV 11

您可以使用一个非常简单的解决方案,如下所示:

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])
Run Code Online (Sandbox Code Playgroud)

输出:

'2031'


Bos*_*hoi 9

正则表达式解决方案:

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))
Run Code Online (Sandbox Code Playgroud)

输出:

[2, 0, 3, 1]
2031
Run Code Online (Sandbox Code Playgroud)

使用蛮力循环逻辑的解决方案:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

[2, 0, 3, 1]
Run Code Online (Sandbox Code Playgroud)