计算字符串中子字符串出现的次数 [英] Count number of occurrences of a substring in a string
本文介绍了计算字符串中子字符串出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算给定子字符串出现在 Python 字符串中的次数?
例如:
<预><代码>>>>'foo bar foo'.numberOfOccurrences('foo')2 解决方案
string.count(substring)
,如:
更新:
正如评论中所指出的,这是针对非重叠出现的方法.如果您需要计算重叠出现的次数,最好在以下位置查看答案:"Python regex找到所有重叠的匹配项?",或者查看我下面的其他答案.
How can I count the number of times a given substring is present within a string in Python?
For example:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
解决方案
string.count(substring)
, like in:
>>> "abcdabcva".count("ab")
2
Update:
As pointed up in the comments, this is the way to do it for non overlapping occurrences. If you need to count overlapping occurrences, you'd better check the answers at: "Python regex find all overlapping matches?", or just check my other answer below.
这篇关于计算字符串中子字符串出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文