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

2024-09-24 22:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有:

str = "Hello! My name is Barney!"

是否有一个或两行方法来检查此字符串是否包含两个!


Tags: 方法字符串namehelloismystrbarney
3条回答

使用^{}方法:

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

顺便说一下,不要使用str作为变量名。它隐藏了内置的str函数。

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

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,并且变量中的字符被替换了,出于其他原因,那么您可以简单地减去这些变量。可能不是这样,而是值得思考的问题。

是的,使用字符串的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.

>>>

相关问题 更多 >