如何计算特定字符串中某个元素的出现次数?

7
在Python中,我记得有一个函数可以做到这一点。
.count?
“大棕色的狐狸是棕色的” brown = 2。

你在哪里搜索以尝试找到这个“count”函数?是哪个库参考网站?还是哪个教程网站? - S.Lott
2个回答

27

为什么不先阅读文档呢,它非常简单:

>>> "The big brown fox is brown".count("brown")
2

19

如果你是一个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']

记住,在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.

这会显示该方法的文档字符串 - 一些帮助文本,你应该养成在自己的方法中添加文档字符串的习惯。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接