Reputation: 2187
Lets say I have:
str = "Hello! My name is Barney!"
Is there a one or two line method to check if this string contains two !
?
Upvotes: 11
Views: 37721
Reputation: 141
Except str.count
, I think filter
is also a feasible way:
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
Upvotes: 0
Reputation: 764
There are a bunch of one liner ways to find the number of characters in a string:
string = "Hello! My name is Barney!"
Ways:
string.count('!') == 2 #best way
or
len([x for x in string if x == '!']) == 2 #len of compresion with if
or
len(string)-len(string.replace('!','')) == 2 #len of string - len of string w/o character
or
string[string.find('!')+1:].find('!')>0 #find it, and find it again, at least twice
count
is the best, but I love to think of other ways, because I sometimes find redundant code/variables that way, depending on what you are doing of course. Say if you already have the len of the string and the len of the string with the characters replaced in variables, for some other reason, then you can simply subtract those variables. Probably not the case, but something to think about.
Upvotes: 0
Reputation:
Yes, you can get the solution in one line easily with the count
method of a string:
>>> # 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.
>>>
Upvotes: 20