python 如何计算某个字符串中某事发生的次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1666700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count the number of times something occurs inside a certain string?
提问by TIMEX
In python, I remember there is a function to do this.
在python中,我记得有一个函数可以做到这一点。
.count?
。数数?
"The big brown fox is brown" brown = 2.
“棕色的大狐狸是棕色的”棕色 = 2。
回答by ghostdog74
why not read the docs first, it's very simple:
为什么不先阅读文档,很简单:
>>> "The big brown fox is brown".count("brown")
2
回答by Dave Webb
One thing worth learning if you're a Python beginner is how to use interactive modeto help with this. The first thing to learn is the dir
functionwhich will tell you the attributes of an object.
如果您是 Python 初学者,值得学习的一件事是如何使用交互模式来帮助解决这个问题。首先要学习的是dir
函数,它会告诉你一个对象的属性。
>>> mystring = "The big brown fox is brown"
>>> dir(mystring)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g
t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__
', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '
__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdi
git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lst
rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit'
, 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', '
translate', 'upper', 'zfill']
Remember, in Python, methods are also attributes. So now he use the help
functionto inquire about one of the methods that looks promising:
请记住,在 Python 中,方法也是属性。所以现在他用help
函数来查询一个看起来很有前景的方法:
>>> help(mystring.count)
Help on built-in function count:
count(...)
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are interpreted
as in slice notation.
This displays the docstringof the method - some help text which you should get in to the habit of putting in your own methods too.
这将显示方法的文档字符串——一些帮助文本,您也应该养成放入自己的方法的习惯。