2013-10-08 165 views

回答

9

是的,你可以用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. 

>>> 
+0

'如果mystr.count(“!”)== 2:打印TRUE'可以写得更简洁就像'print mystr.count('!')== 2'一样,如果你想要可能的'False'打印输出,我认为你在大多数情况下都是这样。 – kqr

+0

@kqr - 的确如此。我只是在'if'块中使用'count'来演示。 – iCodez

3

使用str.count方法:

>>> s = "Hello! My name is Barney!" 
>>> s.count('!') 
2 

BTW,不要使用str可变名称。它阴影内置str功能。

1

还有一堆的一个衬垫的方法来找到字符串中的字符数:

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是最好的,但我喜欢另想办法,因为我有时会发现冗余代码/变量的方式,这取决于你正在做的,当然什么。假如你已经有了字符串的len和字符串的len,并且在变量中替换了字符,出于某种其他原因,那么你可以简单地减去这些变量。可能不是这种情况,但需要考虑。

0

使用

str.count("!") 

所以:

if str.count("!") == 2: 
    return True 
0

除了str.count,我觉得filter也是一个可行的办法:

的Python 2:

>>> len(filter(lambda x: x == '!', "Hello! My name is Barney!")) 
2 

的Python 3:

>>> len(list(filter(lambda x: x == '!', "Hello! My name is Barney!"))) 
2 
相关问题