0

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

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

so when there is no "m" in "hello" python returns true value (as it's not empty string), I thought it would be equal zero as there is no "m" in "hello" so it count zeroand boolean value would be false?
Hey sorry I missed your response. If that's what you want, then it should've been 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).
0

The output of the boolean operations between the strings depends on following things:

  • Python considers empty strings as having boolean value of ‘false’ and non-empty string as having boolean value of ‘true’.
  • For ‘and’ operator if left value is true, then right value is checked and returned. If left value is false, then it is returned
  • For ‘or’ operator if left value is true, then it is returned, otherwise if left value is false, then right value is returned.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.