gpt4 book ai didi

python - 在不使用内置函数的情况下计算子字符串的出现次数

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:48 26 4
gpt4 key购买 nike

我的老师要求我找到一种方法来计算单词“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)

最佳答案

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

关于python - 在不使用内置函数的情况下计算子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52690468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com