[英]How to count the number of times something occurs inside a certain string?
In python, I remember there is a function to do this. 在python中,我记得有一个函数可以做到这一点。
.count? 。计数?
"The big brown fox is brown" brown = 2. “大棕狐狸是棕”棕= 2。
why not read the docs first, it's very simple: 为什么不先阅读文档,这很简单:
>>> "The big brown fox is brown".count("brown")
2
One thing worth learning if you're a Python beginner is how to use interactive mode to help with this. 如果您是Python初学者,则值得学习的一件事是如何使用交互式模式来帮助解决此问题。 The first thing to learn is the
dir
function which will tell you the attributes of an object. 首先要学习的是
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. 请记住,在Python中,方法也是属性。 So now he use the
help
function to inquire about one of the methods that looks promising: 因此,现在他使用
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 docstring of the method - some help text which you should get in to the habit of putting in your own methods too. 这将显示方法的文档字符串 -一些帮助文本,您也应该养成放入自己的方法的习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.