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

7 投票
2 回答
18977 浏览
提问于 2025-04-15 15:38

在Python中,我记得有一个函数可以做到这一点。

.count?

“大棕色狐狸是棕色的”

brown = 2。

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.

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

27

为什么不先看看文档呢?这很简单:

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

撰写回答