Python 确定子字符串在字符串中出现的次数
我有一个字符串“ABChi hi”,我想写一个程序来确定子字符串“hi”在主字符串中出现的次数。到目前为止,我的代码如下所示:Python 确定子字符串在字符串中出现的次数,python,string,Python,String,我有一个字符串“ABChi hi”,我想写一个程序来确定子字符串“hi”在主字符串中出现的次数。到目前为止,我的代码如下所示: the_word = "ABChi hi" new_word = the_word.split() count = 0 for i in new_word: if i == "hi": count += 1 问题是当我拆分字符串时 ["ABChi", "hi"] 这只会帮助我计算发生的两个h
the_word = "ABChi hi"
new_word = the_word.split()
count = 0
for i in new_word:
if i == "hi":
count += 1
问题是当我拆分字符串时
["ABChi", "hi"]
这只会帮助我计算发生的两个hi中的一个,尽管正确答案是2。有人对如何获得正确答案有什么想法吗?呃
您可以执行以下操作:“ABChi hi”.count(“hi”)
。。
>>> "ABChi hi".count("hi")
2
>>>