Occurence of characters in common in two strings

前端 未结 2 965
傲寒
傲寒 2020-12-22 00:57

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 = \'b

相关标签:
2条回答
  • 2020-12-22 01:27

    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)
    
    0 讨论(0)
  • 2020-12-22 01:33

    Pretty straightforward:

    count = 0
    
    for letter in set(string1):
      count += string2.count(letter)
    
    print(count)
    
    0 讨论(0)
提交回复
热议问题