>>> # I named it 'mystr' because it is a bad practice to name a variable 'str'
>>> # Doing so overrides the built-in
>>> mystr = "Hello! My name is Barney!"
>>> mystr.count("!")
2
>>> if mystr.count("!") == 2:
... print True
...
True
>>>
>>> # Just to explain further
>>> help(str.count)
Help on method_descriptor:
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.
>>>
使用^{} 方法:
顺便说一下,不要使用
str
作为变量名。它隐藏了内置的str
函数。有很多一行的方法可以找到字符串中的字符数:
方法:
或者
或者
或者
count
是最好的,但是我喜欢考虑其他的方法,因为我有时会发现这样的冗余代码/变量,这当然取决于您在做什么。假设您已经有了字符串的len和字符串的len,并且变量中的字符被替换了,出于其他原因,那么您可以简单地减去这些变量。可能不是这样,而是值得思考的问题。是的,使用字符串的
count
方法可以很容易地在一行中得到解决方案:相关问题 更多 >
编程相关推荐