循环字符串 - 添加和跳过字符

问题描述 投票:0回答:1

我有下面的代码(这是错误的),我想计算“car”这个词出现的次数。所以这里的输出将是 2。

word="cccccccaaaaaaaaaaarrrrrccar"
count=0
for letter in word:
        if letter == "c":
            if letter=="a":
                if letter=="r":
        count+=1

print(count)

我该怎么做?

python-3.x string loops iteration
1个回答
0
投票

根据评论,您可以删除重复的字符,使用

str.join
将它们连接起来,然后使用
str.count
来计算单词“car”出现的次数:

def remove_duplicate_characters(word):
    if word == "":
        return ""

    i = iter(word)
    prev = next(i)
    yield prev

    for ch in i:
        if ch == prev:
            continue
        prev = ch
        yield ch


word = "cccccccaaaaaaaaaaarrrrrccar"

print("".join(remove_duplicate_characters(word)).count("car"))

打印:

2
© www.soinside.com 2019 - 2024. All rights reserved.