让我们说:
str = "Hello! My name is Barney!"
Run Code Online (Sandbox Code Playgroud)
是否有一个或两个行方法来检查此字符串是否包含两个!
?
iCo*_*dez 10
是的,您可以count
使用字符串的方法轻松地在一行中获得解决方案:
>>> # 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.
>>>
Run Code Online (Sandbox Code Playgroud)