可以使用Python内置的count()函数来计算一个字符串中另一个字符串出现的次数。以下是代码示例:
def count_occurrences(main_str, sub_str):
count = 0
start_index = 0
while True:
index = main_str.find(sub_str, start_index)
if index == -1:
break
count += 1
start_index = index + len(sub_str)
return count
# 使用这个函数来查找字符串“hello world”中“lo”出现的次数
main_str = "hello world"
sub_str = "lo"
count = count_occurrences(main_str, sub_str)
print("在字符串 {} 中,{} 出现的次数是: {}".format(main_str, sub_str, count))
输出:在字符串 hello world 中,lo 出现的次数是: 2
以上代码中,我们定义了一个count_occurrences()函数,该函数接受两个参数:主字符串和子字符串。对于计算出现次数不正确的问题,我们使用了一个while循环。这个循环查找子字符串在主字符串中的位置并递增计数器变量。如果在主字符串中找不到子字符串并且循环应该终止时,我们退出循环并返回计数器的值。最后,使用传递给函数的主字符串和子字符串调用函数,并打印出子字符串在主字符串中出现的次数。