Count the Number of matching characters in a pair of string in Python

We are given two strings and need to find the count of characters in the first string that are also present in the second string. Python provides several approaches to solve this problem efficiently.

Using Set Intersection

The set function gives us unique values of all elements in a string. We use the & operator to find common elements between the two strings ?

Example

strA = 'Tutorials Point'
uniq_strA = set(strA)
print("Given String:", strA)

strB = 'aeio'
uniq_strB = set(strB)
print("Search character strings:", strB)

common_chars = uniq_strA & uniq_strB
print("Count of matching characters are:", len(common_chars))
print("Common characters:", common_chars)
Given String: Tutorials Point
Search character strings: aeio
Count of matching characters are: 3
Common characters: {'i', 'o', 'a'}

Using Regular Expression Search

We use the search() function from the re module. We increment a counter when the search result finds a match ?

Example

import re

strA = 'Tutorials Point'
print("Given String:", strA)

strB = 'aeio'
print("Search character strings:", strB)

cnt = 0
for i in strA:
    if re.search(i, strB):
        cnt = cnt + 1

print("Count of matching characters are:", cnt)
Given String: Tutorials Point
Search character strings: aeio
Count of matching characters are: 5

Using Simple Loop with 'in' Operator

A more straightforward approach using Python's in operator to check character presence ?

Example

strA = 'Tutorials Point'
strB = 'aeio'

print("Given String:", strA)
print("Search character strings:", strB)

count = 0
for char in strA:
    if char in strB:
        count += 1

print("Count of matching characters are:", count)
Given String: Tutorials Point
Search character strings: aeio
Count of matching characters are: 5

Comparison of Methods

Method Counts Duplicates? Performance Best For
Set Intersection No Fast Unique character count
Regular Expression Yes Slower Complex pattern matching
Simple Loop Yes Fast Total occurrence count

Conclusion

Use set intersection for counting unique matching characters. Use simple loop with in operator for counting total occurrences including duplicates. Regular expressions are best for complex pattern matching scenarios.

Updated on: 2026-03-15T18:01:45+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements