Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

python - Occurence of characters in common in two strings

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pretty straightforward:

count = 0

for letter in set(string1):
  count += string2.count(letter)

print(count)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...