Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定子字符串在字符串中出现的次数_Python_String - Fatal编程技术网

Python 确定子字符串在字符串中出现的次数

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

我有一个字符串“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"]
这只会帮助我计算发生的两个hi中的一个,尽管正确答案是2。有人对如何获得正确答案有什么想法吗?

您可以执行以下操作:
“ABChi hi”.count(“hi”)
。。
>>> "ABChi hi".count("hi")
2
>>>