-1

I'm struggling with what seems to be a simple case. I got to the point where I can search for specific input and I let the program print how many times the given input is within each element of the list.

So take for instance the following list:

title = ['hello 2017', 'hello 2019', 'bye 2017']

My (very simple) code:

for s in title:
    count = s.count('2017')
    print(count)

Ouput:

1
0
1

I tried to replace print(count) with the following:

    if count == 1:
        total =+ 1

print(total)

This only gives ' 1 ' when being printed.

I feel kinda dumb asking this question, but it would be nice if someone could give a hint.

4 Answers4

1

Can you try the following:

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    total += count
    print(total)

Output:

1
1
2

or

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    if count >= 1:
        total += count
        print(total)
    else:
        print(0)

Output:

1
0
2
Jeril
  • 7,858
  • 3
  • 52
  • 69
0
title = [ hello 2017, hello 2019, bye 2017 ]
for s in title:
    count = s.count('2017')
    print(count)

If i understand your question correctly,Yes that's correct and you need to understand that

i+=1 is the same as i=i+1, whereas i=+1 just means i=(+1).

The difference between '+=' and '=+'?

So you have to rewrite your code as :

title = ['hello 2017', 'hello 2019', 'bye 2017']
total = 0
for s in title:
    count = s.count('2017')
    if count == 1:
        total += count
    else:
        print("Count not equals to 1")
print(total)
Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
0

I could have totally misunderstood your question but here it goes:

import re

title = ['hello 2017', 'hello 2019', 'bye 2017']

for item in title:
    numbers = re.findall(r"(\d)", item)
    total = 0
    for num in numbers:
        try:
            total += int(num)
        except:
            pass
    print(total)

output:

10
12
10

It's added up each of the digits in the years

Ari
  • 5,301
  • 8
  • 46
  • 120
0

You can count the occurrences into a list and use sum() on it to get the total

title = ['hello 2017', 'hello 2019', 'bye 2017']
occurrences = [s.count('2017') for s in title]
print(*occurrences) # 1 0 1, add sep='\n' to print vertically
print(sum(occurrences)) # 2
Guy
  • 46,488
  • 10
  • 44
  • 88