如何检查一个字符串中是否包含两个相同的字符?

10

假设我有:

str = "Hello! My name is Barney!"

有没有一种一两行的方法来检查这个字符串是否包含两个 !


而稍微有趣的变化是快速检查是否有任何重复字符... - beroe
5个回答

18

是的,你可以很容易地用字符串的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,我假设在大多数情况下你是需要这个输出的。 - kqr
@kqr - 确实。我只是在演示如何在if块中使用count - user2555451

4
使用 str.count 方法:
>>> s = "Hello! My name is Barney!"
>>> s.count('!')
2

顺便提醒一下,不要使用 str 作为变量名。它会覆盖内置的 str 函数。


1

使用

str.count("!")

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

0

有很多一行代码的方法可以找到字符串中字符的数量:

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 是最好的方法,但我喜欢想其他的方法,因为有时候这样可以找到冗余的代码/变量,当然这要根据你所做的事情而定。比如说,如果你已经在某个变量中得到了字符串长度以及替换字符后的字符串长度,那么你就可以简单地将这两个变量相减。可能情况不是这样的,但这是需要思考的。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接