Python|在连续字符之间计算 K 个字符
有时,在处理字符串时,我们可能会遇到需要检查连续字符之间每个字符的计数的问题。这种类型的问题可以在日常和网络开发领域有应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们迭代列表,计算每个字符之间的 K 个字符。
# Python3 code to demonstrate working of
# Count K character between consecutive characters
# Using loop
# initializing string
test_str = "g...f..g.i..s....b..e....s...t"
# printing original string
print("The original string is : " + test_str)
# initializing K
K = '.'
# Count K character between consecutive characters
# Using loop
count = 0
res = []
for ele in test_str:
if ele == K:
count += 1
else:
res.append(count)
count = 0
res = res[1:]
# printing result
print("List of character count : " + str(res))
输出 :
The original string is : g...f..g.i..s....b..e....s...t
List of character count : [3, 2, 1, 2, 4, 2, 4, 3]
方法 #2:使用列表理解 + findall()
这是可以解决此问题的另一种方式。在此,我们使用 findall() 检查出现的 K字符,并使用列表推导来迭代字符串。
# Python3 code to demonstrate working of
# Count K character between consecutive characters
# Using list comprehension + findall()
import re
# initializing string
test_str = "g---f--g-i--s----b--e----s---t"
# printing original string
print("The original string is : " + test_str)
# Count K character between consecutive characters
# Using list comprehension + findall()
res = [len(ele) for ele in re.findall('(?<=[a-z])-*(?=[a-z])', test_str)]
# printing result
print("List of character count : " + str(res))
输出 :
The original string is : g---f--g-i--s----b--e----s---t
List of character count : [3, 2, 1, 2, 4, 2, 4, 3]