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

0

5 Answers 5

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

@taji01That's a whole different question, especially because you seem to be looking for overlapping matches. count counts non-overlapping matches. See here.
7

Use regular expression:

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

or map:

>>> sum(map(s.count, ['l','o']))
5

Comments

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'

Comments

1
s = "hello world"
sum([s.count(x) for x in ['l','o']])

Output: 5

Comments

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'])

1 Comment

This is basically O(n^2) where n is the strings length, as opposed to the other answer using a Counter...

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.