假设我有:
str = "Hello! My name is Barney!"
有没有一种一两行的方法来检查这个字符串是否包含两个 !
?
是的,你可以很容易地用字符串的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.
>>>
False
输出,那么 if mystr.count('!') == 2: print True
可以更简洁地写成 print mystr.count('!') == 2
,我假设在大多数情况下你是需要这个输出的。 - kqrcount
。 - user2555451str.count
方法:>>> s = "Hello! My name is Barney!"
>>> s.count('!')
2
顺便提醒一下,不要使用 str
作为变量名。它会覆盖内置的 str
函数。
使用
str.count("!")
if str.count("!") == 2:
return True
有很多一行代码的方法可以找到字符串中字符的数量:
string = "Hello! My name is Barney!"
string.count('!') == 2 #best way
或者
len([x for x in string if x == '!']) == 2 #len of compresion with if
或者
len(string)-len(string.replace('!','')) == 2 #len of string - len of string w/o character
或者
string[string.find('!')+1:].find('!')>0 #find it, and find it again, at least twice
count
是最好的方法,但我喜欢想其他的方法,因为有时候这样可以找到冗余的代码/变量,当然这要根据你所做的事情而定。比如说,如果你已经在某个变量中得到了字符串长度以及替换字符后的字符串长度,那么你就可以简单地将这两个变量相减。可能情况不是这样的,但这是需要思考的。