'How to count number of letter occurences in multiple strigns simultaneusly using Counter in Python? Is + correct to use?
I am trying to count how many times particular letters occur in given strings. Am I using Counter correctly? The question is can I calculate it from two strings at once using +? It looks like working, but Im not sure if its correct. Example - to find how many times letters t r u e occur in strings
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
from collections import Counter
lowercase_name1 = str.lower(name1)
lowercase_name2 = str.lower(name2)
cntr_true = Counter(lowercase_name1 + lowercase_name2)
total_letters_true = cntr_true["t"] + cntr_true["r"] +
cntr_true["u"] + cntr_true["e"]
number = total_letters_true
print(f"{number}")
Result:
What is your name?
True
What is their name?
Tr ue
8
Solution 1:[1]
from collections import Counter
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
list1=list(str.lower(name1+name2))
res=Counter(list1)
print("Letter Count: ")
for key in res:
print(key, ':', res[key])
This code will count occurance of each letter in name1 and name2

Below Code will print t r u e occurrence only and exclude rest of letters
from collections import Counter
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
list1=list(str.lower(name1+name2).strip())
res=Counter(list1)
print("Letter Count: ")
t=0
for key in res:
if key=='t' or key=='r' or key=='u'or key=='e':
t=t+res[key]
print(key,':',res[key])
print("Total Counter Value: ",t)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

