Why does this code output 2? 'm' is 0 (false) so why doesn't it output 0 as there is the and expression?
s='hello'
print(s.count('m' and 'l'))
Output:
2
If you print out print('m' and 'l'), you will realize that it will return l.
Python returns False for an empty string, True for anything else.
When you perform Boolean operations on string, the and operation returns the right-most element, and the or operation return the left most element. (Check out Logical Operators on String in Python)
You can play around with more complex examples:
s='helllmmko'
print(s.count('k' and 'm' and 'l')) # prints count of 'l'
print(s.count('k' or 'm' or 'l')) # prints count of 'k'
print(s.count('k' and 'm' or 'l')) # prints count of 'm'
s.count('m') and s.count('l'). But do note that if both 'm' and 'l' exist in variable s, then it will again return the count of the latter, because other non-boolean variables follows the quirk as well (and returns latter, or returns former).The output of the boolean operations between the strings depends on following things:
Reference: https://www.geeksforgeeks.org/g-fact-43-logical-operators-on-string-in-python/
Now to count occurrences of multiple characters in the string - you can do something like below - https://btechgeeks.com/count-occurrences-of-a-single-or-multiple-characters-in-string-and-find-their-index-positions/
# given string
string = "hello"
# given characters list which should be counted
charlist = ['m', 'l']
# traverse the charlist
for char in charlist:
# counting the number of occurences of given character in the string
charcount = string.count(char)
print("count of ", char, "is :", charcount)
Output:
count of m is : 0
count of l is : 2