不使用內置函數計算子字符串的出現次數

2024-07-04 05:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的老师要求我找到一种方法来计算单词“bob”在没有str.count()的任何随机字符串变量中的出现次数。所以我做了

a = "dfjgnsdfgnbobobeob bob"
compteurDeBob = 0
for i in range (len(a) - 1):
   if a[i] == "b":
       if a[i+1] == "o":
           if a[i+2] == "b":
               compteurDeBob += 1
print(compteurDeBob)

但我想找到一种方法来做到这一点与任何长度的字如下所示,但我不知道如何做到这一点。。。你知道吗

a = input("random string: ")
word = input("Wanted word: ")
compteurDeBob = 0
for i in range (len(a)-1):

   #... i don't know... 

print(compteurDeBob)

Tags: 方法inforinputlenifcountrange
3条回答

要计算所有重叠出现的次数(如示例中所示),您只需在循环中分割字符串:

a = input("random string: ")
word = input("Wanted word: ")    
cnt = 0

for i in range(len(a)-len(word)+1):
    if a[i:i+len(word)] == word:
        cnt += 1

print(cnt)

你可以用线切片。调整代码的一种方法:

a = 'dfjgnsdfgnbobobeob bob'

counter = 0
value = 'bob'
chars = len(value)

for i in range(len(a) - chars + 1):
    if a[i: i + chars] == value:
        counter += 1

通过sum和生成器表达式,可以用更简洁的方式来编写:

counter = sum(a[i: i + chars] == value for i in range(len(a) - chars + 1))

这是因为bool是Python中int的一个子类,即True/False值分别被认为是10。你知道吗

注意str.count在这里不起作用,因为它only counts non-overlapping matches。如果允许内置,您可以使用^{}。你知道吗

a = input("random string: ")
word = input("Wanted word: ")

count = 0
for i in range(len(a)-len(word)):
    if a[i:i+len(word)] == word:
        count += 1
print(count)

如果希望搜索不区分大小写,则可以使用lower()函数:

a = input("random string: ").lower()
word = input("Wanted word: ").lower()

count = 0
for i in range(len(a)):
    if a[i:i+len(word)] == word:
        count += 1
print(count)

对于用户输入

Hi Bob. This is bob

第一种方法将输出1,第二种方法将输出2

相关问题 更多 >

    热门问题