Reputation: 181
I want to use a for loop to calculate the number of times a character in one string occurs in another string.
e.g. if string1 = 'python' and string2 = 'boa constrictor' then it should calculate to 6 (2 t's, 3 o's, 1 n)
Does anyone know how to do this?
Upvotes: 1
Views: 3460
Reputation: 2038
Use dict comprehension {ch:string2.count(ch) for ch in string1 if ch in string2}
I forgot you need a for
loop and sum over all letters.
count = 0
for ch in string1:
if ch in string2:
count += string2.count(ch)
Upvotes: 0
Reputation: 298582
Pretty straightforward:
count = 0
for letter in set(string1):
count += string2.count(letter)
print(count)
Upvotes: 2