How to count the "s"?

The below code is returning 2. I think it should be returning 7. Guess it isn’t counting the string sassafrass at all?

Code:

how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

for i in how_many_s:
  count_s = 0
  if hasattr(i, 'count'):
    for x in i: 
      if x == 's':
        count_s += 1
print(count_s)
    ```

@petercook0108566555
Happens with me too. :slight_smile:
you just need to define count_s variable outside 1st for loop.

how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
count_s = 0
for i in how_many_s:
  if hasattr(i, 'count'):
    for x in i: 
      if x == 's':
        count_s += 1
print(count_s)

One thinks the idea is to check if the object has the count attribute, and if it does, then use it to accumulate the count_s variable.

>>> how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
>>> count_s = 0
>>> for obj in how_many_s:
    if hasattr(obj, 'count'):
        count_s += obj.count('s')

        
>>> count_s
7
>>> 

Consider,

>>> for obj in how_many_s:
    print (type(obj)),
    if hasattr(obj, 'count'):
        count_s += obj.count('s')
        print (True)
    else:
        print (False)

        
<type 'dict'> False
<type 'str'> True
<type 'int'> False
<type 'list'> True
1 Like

Thanks. Can you remind my why count_s = 0 must be outside the For Loop?

That’s like poetry man…

If you put it inside the loop, will it not be reset to zero each time around?

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.