2

I'm trying to count the letter's 'l' and 'o' in the string below. It seems to work if i count one letter, but as soon as i count the next letter 'o' the string does not add to the total count. What am I missing?

s = "hello world"

print s.count('l' and 'o')

Output: 5

taji01
  • 2,527
  • 8
  • 36
  • 80

4 Answers4

10

You probably mean s.count('l') + s.count('o').

The code you've pasted is equal to s.count('o'): the and operator checks if its first operand (in this case l) is false. If it is false, it returns its first operand (l), but it isn't, so it returns the second operand (o).

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> True and 'x'
'x'
>>> False and 'x'
False
>>> 'x' and True
True
>>> 'x' and False
False
>>> 'x' and 'y'
'y'
>>> 'l' and 'o'
'o'
>>> s.count('l' and 'o')
2
>>> s.count('o')
2
>>> s.count('l') + s.count('o')
5

Official documentation

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • In the case of the string: s = 'azcbobobegghakl' If I want to know the number of times bob occurs. How would I do that. The correct output would be 2. @Wander Nauta – taji01 Sep 05 '15 at 15:14
  • @taji01That's a whole different question, especially because you seem to be looking for *overlapping* matches. `count` counts non-overlapping matches. [See here.](http://stackoverflow.com/q/2970520/182402) – Wander Nauta Sep 05 '15 at 15:17
7

Use regular expression:

>>> import re
>>> len(re.findall('[lo]', "hello world"))
5

or map:

>>> sum(map(s.count, ['l','o']))
5
CT Zhu
  • 52,648
  • 17
  • 120
  • 133
  • Although these methods produce required result, but both of these methods elapse time in seconds if the string is large (say 10000 characters), is there any efficient way? – majid bhatti Jun 05 '21 at 19:51
2

Alternatively, and since you are counting appearances of multiple letters in a given string, use collections.Counter:

>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5

Note that s.count('l' and 'o') that you are currently using would evaluate as s.count('o'):

The expression x and y first evaluates x: if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

In other words:

>>> 'l' and 'o'
'o'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • In the case of the string: s = 'azcbobobegghakl' If I want to know the number of times bob occurs. How would I do that. The correct output would be 2. @alecxe – taji01 Sep 05 '15 at 15:11
0

Count all letters in s:

answer = {i: s.count(i) for i in s}

Then sum any keys (letters) from s:

print(answer['l'] + answer['o'])
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • This is basically `O(n^2)` where `n` is the strings length, as opposed to the [other answer](https://stackoverflow.com/a/32414245/6045800) using a `Counter`... – Tomerikoo Dec 16 '21 at 13:39